詳解Java實現(xiàn)多線程的三種方式
本文實例為大家分享了Java實現(xiàn)多線程的三種方式,供大家參考,具體內(nèi)容如下
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class Main { public static void main(String[] args) { //方法一:繼承Thread int i = 0; // for(; i < 100; i++){ // System.out.println(Thread.currentThread().getName() + " " + i); // if (i == 5) { // ThreadExtendsThread threadExtendsThread = new ThreadExtendsThread(); // threadExtendsThread.start(); // } // } //方法二:實現(xiàn)Runnable // for(i = 0; i < 100; i++){ // System.out.println(Thread.currentThread().getName() + " " + i); // if (i == 5) { // Runnable runnable = new ThreadImplementsRunnable(); // new Thread(runnable).start(); // new Thread(runnable).start(); // } // } //方法三:實現(xiàn)Callable接口 Callable<Integer> callable = new ThreadImplementsCallable(); FutureTask<Integer> futureTask = new FutureTask<>(callable); for(i = 0; i < 100; i++){ System.out.println(Thread.currentThread().getName() + " " + i); if (i == 5) { new Thread(futureTask).start(); new Thread(futureTask).start(); } } try { System.out.println("futureTask ruturn: " + futureTask.get()); } catch (Exception e) { e.printStackTrace(); } } }
方法一,繼承自Thread
public class ThreadExtendsThread extends Thread { private int i; @Override public void run() { for(; i < 100; i++) { System.out.println(getName() + " " + i); } } }
run方法為線程執(zhí)行體,ThreadExtendsThread對象即為線程對象。
方法二,實現(xiàn)Runnable接口
public class ThreadImplementsRunnable implements Runnable { private int i; @Override public void run() { for(; i < 100; i++){ System.out.println(Thread.currentThread().getName() + " " + i); } } }
run方法為線程執(zhí)行體,使用時New一個Thread對象,Runnable對象作為target傳遞給Thread對象。且同一個Runnable對象可作為多個Thread的target,這些線程均共享Runnable對象的實例變量。
方法三,實現(xiàn)Callable接口
import java.util.concurrent.Callable; public class ThreadImplementsCallable implements Callable<Integer> { private int i; @Override public Integer call() throws Exception { for(; i < 100; i++){ System.out.println(Thread.currentThread().getName() + " " + i); } return i; } }
Callable接口類似于Runnable接口,但比對方強大,線程執(zhí)行體為call方法,該方法具有返回值和可拋出異常。使用時將Callable對象包裝為FutureTask對象,通過泛型指定返回值類型??缮院蛘{(diào)用FutureTask的get方法取回執(zhí)行結(jié)果。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助。
相關文章
java如何實現(xiàn)嵌套對象轉(zhuǎn)大map(扁平化)
這篇文章主要介紹了java如何實現(xiàn)嵌套對象轉(zhuǎn)大map(扁平化),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10關于SpringBoot打包測試、生產(chǎn)環(huán)境方式
這篇文章主要介紹了關于SpringBoot打包測試、生產(chǎn)環(huán)境方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09SpringBoot實現(xiàn)阿里云快遞物流查詢的示例代碼
本文將基于springboot實現(xiàn)快遞物流查詢,物流信息的獲取通過阿里云第三方實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2021-10-10Java語言實現(xiàn)簡單FTP軟件 FTP遠程文件管理模塊實現(xiàn)(10)
這篇文章主要為大家詳細介紹了Java語言實現(xiàn)簡單FTP軟件,F(xiàn)TP遠程文件管理模塊的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04