線程初學

1哈爾濱火車站下面有三個火車票代售點,假如哈爾濱到北京的火車票總共是200張,如何用程序來實現三個售票點同時賣票的功能。

package Tread;

class PP implements Runnable{    
    public int tickets=200;       
    String str=new String("123");     
    public void run(){    
        while(true){    
            synchronized(this.str){   
                  
                if(tickets>0){  
                    System.out.println(Thread.currentThread().getName()+"賣出去的票數是:"+tickets--);    
                }  
                else  
                {  
                    break;  
                }  
            }  
        }  
    }  
}  
public class Threade_14 {  
    public static void main(String[] args) {  
        PP pp =new PP();  
        Thread tt1=new Thread(pp);  
        Thread tt2=new Thread(pp);  
        Thread tt3=new Thread(pp);  
        tt1.start();  
        tt2.start();  
        tt3.start();  
    }  
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章