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

開啟執行緒的三種方式

  1 繼承Thread類

  1. publicclass java_thread extends Thread{  
  2.     publicstaticvoid main(String args[])  
  3.     {  
  4.         (new java_thread()).run();  
  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. }  
 

  4 比較

  繼承Thread類的優勢;

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

        (2) 多執行緒同步

 實現Runnable介面的優勢;

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

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

         (3) 增加程式的健壯性,程式碼可以被多個執行緒共享,程式碼個數據獨立

 在函式體使用的優勢;

        (1) 無需繼承Thread或者實現Runnable介面,縮小作用域。