需要在循环处,让抢到票的线程sleep10毫秒即可
public class TestTicket {
public static void main(String[] args) {
GetTicket getTicket = new GetTicket();
new Thread(getTicket,"小王").start();
new Thread(getTicket,"小李").start();
new Thread(getTicket,"黄牛").start();
}
}
class GetTicket implements Runnable{
private int nums =100;
private boolean flag = true; //设置线程停止条件
@Override
public void run() {
while (flag) {
buyTicket();
//所有进程在此暂定一下,模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//同步方法,锁的是this
private synchronized void buyTicket() {
if (nums <= 0) {
flag = false;
return; //程序结束
}
//买票
System.out.println(Thread.currentThread().getName() + "抢到了第" + nums-- + "票");
}
}