黄焖鸡米饭啊 2016-05-19 05:48 采纳率: 50%
浏览 1192
已结题

线程同步 卖票问题 三个车站卖七张票

正确的写法:public class mainclass {
public static void main(String[] args) {
Train A=new Train();
Train B=new Train();
Train C=new Train();
A.start();
B.start();
C.start();

}
}
class Train extends Thread{
public static int ticket=7;
public void run(){
{
A();
}
}
public synchronized void A(){
while (ticket>0){
System.out.println("第"+this.getName()+"站卖出第"+ticket--+"张票");

        } 
     }      
}
出现问题的写法:public class mainclass {
public static void main(String[] args) {
    Train A=new Train();
    Train B=new Train();
    Train C=new Train();
    A.start();
    B.start();
    C.start();      
}

}
class Train extends Thread{
public static int ticket=7;
public void run(){
{
A();
}
}
public synchronized void A(){
while (ticket>0){
System.out.println("第"+this.getName()+"站卖出第"+ticket+"张票");
ticket--;

        } 
     }      
}
在A()函数之中ticket--的位置不同却出现了两种结果。一种将ticket--写在输出语句里,结果正确,但一种写在输出语句之外就会出现线程同步问题,可是我已经在函数前面加了synchronized,为什么会这样,按理来说两者应该一样啊。
  • 写回答

1条回答 默认 最新

  • lbcab 2016-05-19 06:02
    关注

    你把while(ticket) 包含在synchronized同步块中, 导致只有一个线程在跑, 因为一个线程进入while循环后, 直到ticket的值小于0才会退出循环, 才会释放
    synchronized同步块, 这样其他线程才能进入A()方法, 这时候ticket的值已经小于0了.
    将代码改为:

     public void A(){
           while (ticket>0){
                   synchronized(this) {
                    System.out.println("第"+this.getName()+"站卖出第"+ticket+"张票");
                    ticket--;
                                }
                    }
    }
    
    评论

报告相同问题?