共計 1046 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
Java 開啟多線程的常見方法有以下幾種:
- 繼承 Thread 類:定義一個類繼承 Thread 類,并重寫 run() 方法,然后創(chuàng)建該類的實例,并調(diào)用 start() 方法啟動線程。
class MyThread extends Thread {public void run() {// 線程執(zhí)行的代碼}
}
MyThread thread = new MyThread();
thread.start();
- 實現(xiàn) Runnable 接口:定義一個類實現(xiàn) Runnable 接口,并實現(xiàn)其 run() 方法,然后創(chuàng)建 Thread 類的實例,將 Runnable 對象作為參數(shù)傳遞給 Thread 對象,最后調(diào)用 Thread 的 start() 方法啟動線程。
class MyRunnable implements Runnable {public void run() {// 線程執(zhí)行的代碼}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
- 使用 Callable 和 Future:定義一個類實現(xiàn) Callable 接口,并實現(xiàn)其 call() 方法,然后創(chuàng)建 ExecutorService 對象,將 Callable 對象提交給 ExecutorService 的 submit() 方法,返回一個 Future 對象,通過調(diào)用 Future 對象的 get() 方法獲取線程的返回值。
class MyCallable implements Callable {public Integer call() throws Exception {
// 線程執(zhí)行的代碼
return 1;
}
}
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newFixedThreadPool(1);
Future future = executor.submit(callable);
- 使用線程池:創(chuàng)建一個 ExecutorService 對象,通過調(diào)用其方法來提交 Runnable 或 Callable 任務(wù),線程池會自動管理線程的生命周期。
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Runnable() {public void run() {// 線程執(zhí)行的代碼}
});
這些方法都可以用來創(chuàng)建并啟動一個新的線程,根據(jù)具體情況選擇使用。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完