需求:模拟三个窗口共卖100张票
public class SellTicketsDemo {
public static void main(String[] args) {
SellTickets st=new SellTickets();
Thread t1=new Thread(st,"窗口1");
Thread t2=new Thread(st,"窗口2");
Thread t3=new Thread(st,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
public class SellTickets implements Runnable{
private int tickets=100;
private Object obj=new Object();
@Override
public void run() {
while(true) {
//synchronized(任意对象):同步代码块
synchronized(obj) {
if(tickets>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票");
tickets--;
}
}
}
}
}