public class Demo05 extends Thread{
static Object obj=new Object();
//假如有100张票
static int count=100;
@Override
public void run() {
while (true){
try {
Thread.sleep(2000);
synchronized (obj){
if(count>0){
System.out.println("当前卖出的是:"+count+"号票!"+Thread.currentThread().getName());
count--;
}else{
System.out.println("票卖完了!");
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Demo05 d=new Demo05();
d.start();
Demo05 d2=new Demo05();
d2.start();
}
}
运行效果: