第9周總結&實驗報告7

完成火車站售票程序的模擬。java

要求:
(1)總票數1000張;
(2)10個窗口同時開始賣票;
(3)賣票過程延時1秒鐘;
(4)不能出現一票多賣或賣出負數號票的狀況。
一:實驗代碼多線程

package first;
class MyThread implements Runnable{
    private int ticket = 1 ;    
    public void run(){
        for(int i=0;i<1000;i++){
            synchronized(this){ 
                if(ticket<=1000){  
                    try{
                        Thread.sleep(1000) ;    
                    }catch(InterruptedException e){
                        e.printStackTrace() ;
                    }
                        System.out.println(Thread.currentThread().getName()+"賣票:ticket = " + ticket++ );
                }
            }
        }
    }   
}
public class Demo{
    public static void main(String args[]){
        MyThread my = new MyThread();
        Thread d1 = new Thread(my,"窗口A");
        Thread d2 = new Thread(my,"窗口B");
        Thread d3 = new Thread(my,"窗口C");   
        Thread d4 = new Thread(my,"窗口D");
        Thread d5 = new Thread(my,"窗口E");
        Thread d6 = new Thread(my,"窗口F");
        Thread d7 = new Thread(my,"窗口G");
        Thread d8 = new Thread(my,"窗口H");
        Thread d9 = new Thread(my,"窗口I");
        Thread d10 = new Thread(my,"窗口J");
        d4.setPriority(Thread.MIN_PRIORITY) ;   
        d5.setPriority(Thread.MAX_PRIORITY) ;   
        d6.setPriority(Thread.NORM_PRIORITY) ;  
        d1.start() ;    
        d2.start() ;   
        d3.start() ;    
        d4.start() ;    
        d5.start() ;    
        d6.start() ;   
        d7.start() ;    
        d8.start() ;    
        d9.start() ;    
        d10.start() ;
    }
}
結果截圖

 

 學習總結:學習

 1 對於java IO操做文件類——File的介紹與對File類主要方法與構造類的瞭解this

2 Java中多線程的實現主要是經過繼承Thread類或實現Runnable接口。其中Runnable接口能夠資源共享。但無論使用哪一種方法都要經過覆寫run();在實例化的時候經過調用start()方法來啓動多線程。spa

相關文章
相關標籤/搜索