1. 程式人生 > >Thread與Runnable區別

Thread與Runnable區別

Thread和Runnable區別

執行多執行緒操作可以選擇
  • 繼承Thread類
  • 實現Runnable介面
1.繼承Thread類以賣票視窗舉例,一共5張票,由3個視窗進行售賣(3個執行緒)。程式碼:
package thread;
public class ThreadTest {
	public static void main(String[] args) {
		MyThreadTest mt1 = new MyThreadTest("視窗1");
		MyThreadTest mt2 = new MyThreadTest("視窗2");
		MyThreadTest mt3 = new MyThreadTest("視窗3");
		mt1.start();
		mt2.start();
		mt3.start();
	}
}
class MyThreadTest extends Thread{
	private int ticket = 5;    
	private String name;
	public MyThreadTest(String name){
		this.name = name;
	}
    public void run(){    
         while(true){  
             if(ticket < 1){    
                break;  
             }   
             System.out.println(name + " = " + ticket--);    
         }    
    } 
}
執行結果:
視窗1 = 5
視窗1 = 4
視窗1 = 3
視窗1 = 2
視窗1 = 1
視窗2 = 5
視窗3 = 5
視窗2 = 4
視窗3 = 4
視窗3 = 3
視窗3 = 2
視窗3 = 1
視窗2 = 3
視窗2 = 2
視窗2 = 1
結果一共賣出了5*3=15張票,這違背了"5張票"的初衷。造成此現象的原因就是:
		MyThreadTest mt1 = new MyThreadTest("視窗1");
		MyThreadTest mt2 = new MyThreadTest("視窗2");
		MyThreadTest mt3 = new MyThreadTest("視窗3");
		mt1.start();
		mt2.start();
		mt3.start();
一共建立了3個MyThreadTest物件,而這3個物件的資源不是共享的,即各自定義的ticket=5是不會共享的,因此3個執行緒都執行了5次迴圈操作。2.實現Runnable介面同樣的例子,程式碼:
package thread;
public class RunnableTest {
	public static void main(String[] args) {
		MyRunnableTest mt = new MyRunnableTest();
		Thread mt1 = new Thread(mt,"視窗1");
		Thread mt2 = new Thread(mt,"視窗2");
		Thread mt3 = new Thread(mt,"視窗3");
		mt1.start();
		mt2.start();
		mt3.start();
	}
}
class MyRunnableTest implements Runnable{
	private int ticket = 5;    
	public void run(){    
         while(true){  
    		 if(ticket < 1){    
    			 break;  
    		 }    
    		 System.out.println(Thread.currentThread().getName() + " = " + ticket--);    
         }    
    } 
}
結果:
視窗1 = 5
視窗1 = 2
視窗3 = 4
視窗2 = 3
視窗1 = 1
結果賣出了預期的5張票。原因在於:
		MyRunnableTest mt = new MyRunnableTest();
		Thread mt1 = new Thread(mt,"視窗1");
		Thread mt2 = new Thread(mt,"視窗2");
		Thread mt3 = new Thread(mt,"視窗3");
		mt1.start();
		mt2.start();
		mt3.start();
只建立了一個MyRunnableTest物件,而3個Thread執行緒都以同一個MyRunnableTest來啟動,所以他們的資源是共享的。