s-day06--.线程安全-卖票案例的实现
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user