s-day06--.线程安全-卖票案例的实现

This commit is contained in:
xx
2026-10-19 14:17:00 +08:00
parent 703ebdfa6e
commit e501056e61
2 changed files with 52 additions and 0 deletions
@@ -0,0 +1,27 @@
package com.inmind.thread_safe04;
// 1.定义卖票任务,只有100张票,有票就卖
public class TicketTask implements Runnable{
int ticketCount = 100;//100张票
@Override
public void run() {
//有票就卖
while (true) {
if (ticketCount > 0) {
//卖票:需要耗时5ms
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticketCount + "张票");
ticketCount--;
} else {
// 没有票就关闭售票窗口
break;
}
}
}
}