JAVA多线程模拟卖票
public class SellTicket implements Runnable {
private int tickets = 100;
private Object object = new Object();
@Override
public void run() {
while (true) {
synchronized (object) {
if (tickets > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + (101 - tickets) + "票");
tickets--;
} else {
System.out.println(Thread.currentThread().getName() + ":NO TICKETS");
return;
}
}
}
}
}
public class Test{
public static void main(String[] args) {
SellTicket st = new SellTicket();
Thread t1 = new Thread(st, "窗口1");
Thread t2 = new Thread(st, "窗口2");
Thread t3 = new Thread(st, "窗口3");
t1.start();
t2.start();
t3.start();
}
}