共計 1118 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 線程的創建方式有以下幾種:
- 繼承 Thread 類:創建一個繼承自 Thread 類的子類,并重寫 run() 方法來定義線程執行的任務。然后可以通過創建子類的實例來創建和啟動線程。
class MyThread extends Thread {public void run() {// 線程執行的任務
}
}
MyThread thread = new MyThread();
thread.start();
- 實現 Runnable 接口:創建一個實現了 Runnable 接口的類,并實現其 run() 方法來定義線程執行的任務。然后可以通過創建 Runnable 實現類的實例來創建 Thread 實例,并調用 start() 方法來啟動線程。
class MyRunnable implements Runnable {public void run() {// 線程執行的任務
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
- 使用匿名內部類:可以在創建 Thread 對象時使用匿名內部類來實現 run() 方法。這種方式比較簡潔,適用于定義較為簡單的線程任務。
Thread thread = new Thread() {public void run() {// 線程執行的任務
}
};
thread.start();
- 使用 Callable 和 Future:通過創建實現 Callable 接口的類,并實現其 call() 方法來定義線程執行的任務。然后可以使用 ExecutorService 的 submit() 方法提交 Callable 任務,并返回一個 Future 對象,通過 Future 對象可以獲取線程執行結果。
class MyCallable implements Callable<Integer> {public Integer call() throws Exception {// 線程執行的任務,返回一個結果
return 1;
}
}
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new MyCallable());
- 使用線程池:可以使用 ExecutorService 來管理線程池,通過執行 Runnable 或 Callable 任務來創建線程。
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(new Runnable() {public void run() {// 線程執行的任務
}
});
丸趣 TV 網 – 提供最優質的資源集合!
正文完