JAVA多線程的幾種實現方式
?1. 繼承?Thread
?類?
?2. 實現?Runnable
?接口?
- ?原理?:將線程任務解耦,通過?
Runnable
?對象傳遞給?Thread
?構造函數?。 - ?代碼示例?:
public class RunnableDemo implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName() + ":" + i);}}public static void main(String[] args) {Runnable task = new RunnableDemo();Thread t1 = new Thread(task, "Thread-1");Thread t2 = new Thread(task, "Thread-2");t1.start();t2.start();}
}
?優勢?:支持多接口實現,適合資源共享場景?。
?3. 使用?Callable
?和?Future
?
- ?原理?:通過?
Callable
?接口定義可返回結果的任務,配合?FutureTask
?獲取異步計算結果?。 - ?代碼示例?:
import java.util.concurrent.*;public class CallableDemo implements Callable<Integer> {@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i < 5; i++) {sum += i;}return sum;}public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executor = Executors.newSingleThreadExecutor();Future<Integer> future = executor.submit(new CallableDemo());System.out.println("計算結果:" + future.get());executor.shutdown();}
}
?特點?:支持返回值,可處理異常?。
?4. 線程池(ExecutorService
)?
?總結?
?實現方式? | ?適用場景? |
---|
繼承?Thread | 簡單任務,無需資源共享 |
實現?Runnable | 多接口、資源共享 |
Callable /Future | 需要返回結果或處理異常 |
線程池 | 高并發、資源復用 |
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/79201.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/79201.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/79201.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!