實現Callable接口創建線程


創建執行線程有四種方式:

  • 實現implements接口創建線程
  • 繼承Thread類創建線程
  • 實現Callable接口,通過FutureTask包裝器來創建線程
  • 使用線程池創建線程

下面介紹通過實現Callable接口來創建線程。

 1 package com.ccfdod.juc;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.FutureTask;
 6 
 7 /**
 8  * 一、創建執行線程的方式三:實現Callable接口。相較於實現Runnable接口的方式,方法可以有返回值,並且可以拋出異常
 9  * 二、執行Callable方式,需要FutureTask實現類的支持,用於接收運算結果
10  */
11 public class TestCallable {
12     public static void main(String[] args) {
13         ThreadDemo td = new ThreadDemo();
14 
15         // 1.執行Callable方式,需要FutureTask實現類的支持,用於接收運算結果
16         FutureTask<Integer> result = new FutureTask<>(td);
17         new Thread(result).start();
18 
19         // 2.接收線程運算后的結果
20         Integer sum;
21         try {
22             //等所有線程執行完,獲取值,因此FutureTask 可用於 閉鎖
23             sum = result.get();
24             System.out.println("-----------------------------");
25             System.out.println(sum);
26         } catch (InterruptedException | ExecutionException e) {
27             e.printStackTrace();
28         }
29     }
30 }
31 
32 class ThreadDemo implements Callable<Integer> {
33 
34     @Override
35     public Integer call() throws Exception {
36         int sum = 0;
37         for (int i = 0; i <= 100000; i++) {
38             System.out.println(i);
39             sum += i;
40         }
41         return sum;
42     }
43 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM