java併發編程之Thread和Runnable之實例應用(三)

1.Thread版買票:

class MyThread extends Thread{  
    
    private int ticket = 10;  
    private String name;  
    public MyThread(String name){  
        this.name =name;  
    }  
    public void run(){  
        for(int i =0;i<500;i++){  
            if(this.ticket>0){  
                System.out.println(this.name+"賣票---->"+(this.ticket--));  
            }  
        }  
    }  
}

public class ThreadDemo {

    public static void main(String[] args) {  
        MyThread mt1= new MyThread("一號窗口");  
        MyThread mt2= new MyThread("二號窗口");  
        MyThread mt3= new MyThread("三號窗口");  
        mt1.start();  
        mt2.start();  
        mt3.start();  
    }
    
}
結果:

1.Runnable版買票:

public class MyRunnable implements Runnable{  
    private int ticket =10;  
    private String name;  
    public void run(){  
        for(int i =0;i<500;i++){  
            if(this.ticket>0){  
                System.out.println(Thread.currentThread().getName()+"賣票---->"+(this.ticket--));  
            }  
        }  
    }  
}

public class RunnableDemo {

	public static void main(String[] args) {  
         // TODO Auto-generated method stub  
         //設計三個線程  
         MyRunnable mt = new MyRunnable();  
         Thread t1 = new Thread(mt,"一號窗口");  
         Thread t2 = new Thread(mt,"二號窗口");  
         Thread t3 = new Thread(mt,"三號窗口");  
         t1.start();  
         t2.start();  
         t3.start();  
    }
	
}
結果:【顯示的結果次數多了其實會有問題的,這裏其實是需要加入同步操作(即互斥鎖)來保持線程操作的原子性,這後面在說。

結論:

1)Thread版是多個線程分別完成自己的任務。

2)Runnable版是多個線程共同完成一個任務。



發佈了39 篇原創文章 · 獲贊 14 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章