java啟動線程的3種方式對比分析
本文實例為大家分享了java啟動線程的方法,供大家參考,具體內(nèi)容如下
1.繼承Thread
public class java_thread extends Thread{ public static void main(String args[]) { (new java_thread()).run(); System.out.println("main thread run "); } public synchronized void run() { System.out.println("sub thread run "); } }
2.實現(xiàn)Runnable接口
public class java_thread implements Runnable{ public static void main(String args[]) { (new Thread(new java_thread())).start(); System.out.println("main thread run "); } public void run() { System.out.println("sub thread run "); } }
3.直接在函數(shù)體使用
void java_thread() { Thread t = new Thread(new Runnable(){ public void run(){ mSoundPoolMap.put(index, mSoundPool.load(filePath, index)); getThis().LoadMediaComplete(); }}); t.start(); }
4.比較:
實現(xiàn)Runnable接口優(yōu)勢:
1)適合多個相同的程序代碼的線程去處理同一個資源
2)可以避免Java中的單繼承的限制
3)增加程序的健壯性,代碼可以被多個線程共享,代碼和數(shù)據(jù)獨立。
繼承Thread類優(yōu)勢:
1)可以將線程類抽象出來,當(dāng)需要使用抽象工廠模式設(shè)計時。
2)多線程同步
在函數(shù)體使用優(yōu)勢
1)無需繼承thread或者實現(xiàn)Runnable,縮小作用域。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java 實戰(zhàn)項目錘煉之網(wǎng)上花店商城的實現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+jsp+servlet+mysql+ajax實現(xiàn)一個網(wǎng)上花店商城系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11SpringBoot2 Jpa 批量刪除功能的實現(xiàn)
這篇文章主要介紹了SpringBoot2 Jpa 批量刪除功能的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01Java后端產(chǎn)生驗證碼后臺驗證功能的實現(xiàn)代碼
這篇文章主要介紹了Java后臺產(chǎn)生驗證碼后臺驗證功能,本文文字結(jié)合實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06SpringBoot鉤子函數(shù)的實現(xiàn)示例
SpringBoot雖然沒有直接稱為“鉤子函數(shù)”的概念,但可以其他方法實現(xiàn),本文就來介紹一下SpringBoot鉤子函數(shù)的實現(xiàn)示例,感興趣的可以了解一下2024-11-11詳解OpenFeign服務(wù)調(diào)用(微服務(wù))
OpenFeign是Spring Cloud在Feign的基礎(chǔ)上支持了SpringMVC的注解,如@RequesMapping等等,這篇文章主要介紹了OpenFeign服務(wù)調(diào)用的相關(guān)知識,需要的朋友可以參考下2022-07-07