public class Tickets {
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread t1 = new Thread(ticket);
Thread t2 = new Thread(ticket);
Thread t3 = new Thread(ticket);
Thread t4 = new Thread(ticket);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t4.setName("窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket implements Runnable {
private int tickets = 100;
@Override
public void run() {
while(true) {
synchronized(this) {
if(tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//让窗口3卖第10张票
if(tickets == 10){
if(!Thread.currentThread().getName().equals("窗口3")){
continue;
}
}
System.out.println(Thread.currentThread().getName() + "...这是第" + tickets-- + "号票");
}
else break;
}
}
}
} |