Java 并發(fā)編程中如何創(chuàng)建線程
線程是基本的調(diào)度單位,它被包含在進(jìn)程之中,是進(jìn)程中的實際運作單位,它本身是不會獨立存在。一個進(jìn)程至少有一個線程,進(jìn)程中的多個線程共享進(jìn)程的資源。
Java中創(chuàng)建線程的方式有多種如繼承Thread類、實現(xiàn)Runnable接口、實現(xiàn)Callable接口以及使用線程池的方式,線程池將在后面文章中單獨介紹,這里先介紹另外三種方式。
繼承Thread類優(yōu)點:在run方法里可以用this獲取到當(dāng)前線程。
缺點:由于Java不支持多繼承,所以如果繼承了Thread類后就不能再繼承其他類。
public class MyThread extends Thread { /** * 線程要執(zhí)行的任務(wù) */ @Override public void run() { System.out.println('do something...'); } public static void main(String[] args) {//創(chuàng)建線程 MyThread myThread = new MyThread();//啟動線程 myThread.start(); }}實現(xiàn)Runnable接口
優(yōu)點:實現(xiàn)Runnable接口后不影響繼承其他類,以及有利于多個線程資源共享。
缺點:獲取當(dāng)前線程需要調(diào)用Thread.currentThread()。
public class MyThread implements Runnable { /** * 線程要執(zhí)行的任務(wù) */ @Override public void run() { System.out.println('do something...'); } public static void main(String[] args) {//創(chuàng)建兩個線程,并指定相同的任務(wù)Thread thread1 = new Thread(new MyThread()); Thread thread2 = new Thread(new MyThread());//啟動線程 thread1.start(); thread2.start(); }}實現(xiàn)Callable接口
優(yōu)缺點類似于實現(xiàn)Runnable接口,但是實現(xiàn)Callable接口可以有返回值。
public class MyThread implements Callable<String> { /** * 線程要執(zhí)行的任務(wù),并且具有返回值 */ @Override public String call() throws Exception { System.out.println('do something...'); Thread.sleep(3000); return '我是返回值'; } public static void main(String[] args) throws ExecutionException, InterruptedException {//創(chuàng)建異步任務(wù) FutureTask<String> futureTask = new FutureTask(new MyThread());//啟動線程 new Thread(futureTask).start();//阻塞等待線程執(zhí)行完成并返回結(jié)果 String result = futureTask.get(); System.out.println(result); }}
以上就是Java 并發(fā)編程中如何創(chuàng)建線程的詳細(xì)內(nèi)容,更多關(guān)于Java 創(chuàng)建線程的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析2. ASP中常用的22個FSO文件操作函數(shù)整理3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. ASP的Global.asa文件技巧用法5. php測試程序運行速度和頁面執(zhí)行速度的代碼6. html清除浮動的6種方法示例7. SharePoint Server 2019新特性介紹8. ASP中if語句、select 、while循環(huán)的使用方法9. React+umi+typeScript創(chuàng)建項目的過程10. Vue+elementUI下拉框自定義顏色選擇器方式
