public 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 TicketThreadimplements 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 +"张票");
}
}