public class SellTicket{
private static void main(String[] args){
SellWindow window01=new SellWindow();
SellWindow window02=new SellWindow();
SellWindow window03=new SellWindow();
window01.start();
window02.start();
window03.start();
}
}
public class SellWindow extends Thread {
private static int ticketnum=100;//100张票
public void run() {
while (true){
if(ticketnum<=0){
break;
}
//让该线程休眠,模拟售票业务操作耗时
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
//买票
System.out.println("窗口"+Thread.currentThread().getName()+"售出一张票"
+"剩余票数"+(--ticketnum));
}
}
}
因为没有加锁就访问了临界资源 ticketnum