1. 程式人生 > >啟動執行緒的三種方式

啟動執行緒的三種方式

1.繼承Thread

  1. publicclass java_thread extends Thread{  
  2.     publicstaticvoid main(String args[])  
  3.     {  
  4.         (new java_thread()).start();  
  5.         System.out.println("main thread run ");  
  6.     }  
  7.     publicsynchronizedvoid run()  
  8.     {  
  9.         System.out.println("sub thread run ");  
  10.     }  
  11. }  

2.實現Runnable介面
  1. publicclass java_thread implements Runnable{  
  2.     publicstaticvoid main(String args[])  
  3.     {  
  4.         (new Thread(new java_thread())).start();  
  5.         System.out.println("main thread run ");  
  6.     }  
  7.     publicvoid run()  
  8.     {  
  9.         System.out.println("sub thread run ");  
  10.     }  
  11. }  

3.直接在函式體使用
  1. void
     java_thread()  
  2. {  
  3.      Thread t = new Thread(new Runnable(){  
  4.             publicvoid run(){  
  5.             mSoundPoolMap.put(index, mSoundPool.load(filePath, index));  
  6.             getThis().LoadMediaComplete();  
  7.             }});  
  8.         t.start();  
  9. }  
注意:啟動執行緒的方式有且只有呼叫start方法

4.比較:

實現Runnable介面優勢:

1)適合多個相同的程式程式碼的執行緒去處理同一個資源

2)可以避免java中的單繼承的限制

3)增加程式的健壯性,程式碼可以被多個執行緒共享,程式碼和資料獨立。

繼承Thread類優勢:

1)可以將執行緒類抽象出來,當需要使用抽象工廠模式設計時。

2)多執行緒同步

在函式體使用優勢

1)無需繼承thread或者實現Runnable,縮小作用域。