我們先來看段範例程式碼
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(); // } // } //方法二:实现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(); // } // } //方法三:实现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(); } } }
接下來我們來詳細探討下Java 實作多執行緒的幾種方式
方法一,繼承自Thread
public class ThreadExtendsThread extends Thread { private int i; @Override public void run() { for(; i < 100; i++) { System.out.println(getName() + " " + i); } } }
run方法為執行緒執行體,ThreadExtendsThread物件即為執行緒物件。
方法二,實作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方法為執行緒執行體,使用時New一個Thread對象,Runnable物件作為target傳遞給Thread物件。且同一個Runnable物件可作為多個Thread的target,這些執行緒均共用Runnable物件的實例變數。
方法三,實現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接口,但比對方強大,線程執行體為call方法,該方法具有返回值和可拋出異常。使用時將Callable物件包裝為FutureTask對象,透過泛型指定傳回值類型。可稍候呼叫FutureTask的get方法取回執行結果。
更多Java 實現多線程的幾種方式匯總相關文章請關注PHP中文網!