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