共計 1643 個字符,預計需要花費 5 分鐘才能閱讀完成。
Java 實現多線程的方式有以下幾種:
- 繼承 Thread 類:創建一個類,繼承自 Thread 類,并重寫 run() 方法,在 run() 方法中定義線程要執行的任務。然后創建該類的對象,并調用 start() 方法啟動線程。
class MyThread extends Thread {public void run() {// 線程要執行的任務
}
}
public class Main {public static void main(String[] args) {MyThread thread = new MyThread();
thread.start();}
}
- 實現 Runnable 接口:創建一個類,實現 Runnable 接口,并重寫 run() 方法,在 run() 方法中定義線程要執行的任務。然后創建該類的對象,并將其作為參數傳遞給 Thread 類的構造函數,最后調用 start() 方法啟動線程。
class MyRunnable implements Runnable {public void run() {// 線程要執行的任務
}
}
public class Main {public static void main(String[] args) {MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();}
}
- 使用 Callable 和 Future 接口:創建一個類,實現 Callable 接口,并重寫 call() 方法,在 call() 方法中定義線程要執行的任務。然后創建該類的對象,并將其作為參數傳遞給 ExecutorService 的 submit() 方法,通過 Future 對象可以獲取線程的執行結果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {public String call() {// 線程要執行的任務
return " 任務執行結果 ";
}
}
public class Main {public static void main(String[] args) throws Exception {MyCallable callable = new MyCallable();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(callable);
String result = future.get();
System.out.println(result);
executorService.shutdown();}
}
- 使用線程池:通過 Executor 框架提供的線程池來管理線程的創建和執行。可以使用 Executors 類提供的靜態方法創建不同類型的線程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {executorService.execute(new Runnable() {public void run() {// 線程要執行的任務
}
});
}
executorService.shutdown();}
}
丸趣 TV 網 – 提供最優質的資源集合!
正文完