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
本文分析了一个Java程序,SellTicket类中SellWindow线程并发访问共享资源ticketnum的问题,强调了未加锁可能导致的数据不一致。通过实例展示了如何使用synchronized关键字或Lock接口来确保线程安全。
&spm=1001.2101.3001.5002&articleId=126178821&d=1&t=3&u=678c476af2844537bb7773ce8e482c56)
335

被折叠的 条评论
为什么被折叠?



