啟動執行緒的三種方式
阿新 • • 發佈:2019-01-02
1.繼承Thread
- publicclass java_thread extends Thread{
- publicstaticvoid main(String args[])
- {
- (new java_thread()).start();
- System.out.println("main thread run ");
- }
- publicsynchronizedvoid run()
- {
- System.out.println("sub thread run ");
- }
- }
2.實現Runnable介面
- publicclass java_thread implements Runnable{
- publicstaticvoid main(String args[])
- {
- (new Thread(new java_thread())).start();
- System.out.println("main thread run ");
- }
- publicvoid run()
- {
- System.out.println("sub thread run ");
- }
- }
3.直接在函式體使用
- void
- {
- Thread t = new Thread(new Runnable(){
- publicvoid run(){
- mSoundPoolMap.put(index, mSoundPool.load(filePath, index));
- getThis().LoadMediaComplete();
- }});
- t.start();
- }
4.比較:
實現Runnable介面優勢:
1)適合多個相同的程式程式碼的執行緒去處理同一個資源
2)可以避免java中的單繼承的限制
3)增加程式的健壯性,程式碼可以被多個執行緒共享,程式碼和資料獨立。
繼承Thread類優勢:
1)可以將執行緒類抽象出來,當需要使用抽象工廠模式設計時。
2)多執行緒同步
在函式體使用優勢
1)無需繼承thread或者實現Runnable,縮小作用域。