class MyTest {
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread(10);
new Thread(ticketThread, "小明-").start();
new Thread(ticketThread, "小红-").start();
new Thread(ticketThread, "李华-").start();
}
}
class TicketThread implements Runnable {
/**
* 票数
*/
private int ticket;
/**
* 线程启动开关
*/
private boolean flag = true;
public TicketThread(int ticket) {
this.ticket = ticket;
}
public void run() {
while (flag) {
buy();
}
}
/**
* 买票
*/
public synchronized void buy() {
try {
Thread.sleep(100); // 模拟延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket <= 0) {
flag = false;
System.out.println(Thread.currentThread().getName() + "买票失败 没票了!");
return;
}
System.out.println(Thread.currentThread().getName() + "买票成功 还剩" + --ticket + "张票");
}
}
Java 多线程场景-买票
最新推荐文章于 2023-08-02 16:35:43 发布