1. 程式人生 > >02027_線程池練習:返回兩個數相加的結果

02027_線程池練習:返回兩個數相加的結果

turn mage 操作 ima execution task ati 實現類 res

1、要求:通過線程池中的線程對象,使用Callable接口完成兩個數求和操作。

2、代碼實現:

  (1)Callable接口實現類

 1 import java.util.concurrent.Callable;
 2 
 3 public class MyCallable implements Callable<Integer> {
 4     // 成員變量
 5     int x = 5;
 6     int y = 3;
 7 
 8     // 構造方法
 9     public MyCallable() {
10     }
11 
12     public MyCallable(int
x, int y) { 13 this.x = x; 14 this.y = y; 15 } 16 17 @Override 18 public Integer call() throws Exception { 19 return x + y; 20 } 21 }

  (2)測試類

 1 import java.util.concurrent.ExecutionException;
 2 import java.util.concurrent.ExecutorService;
 3 import java.util.concurrent.Executors;
4 import java.util.concurrent.Future; 5 6 public class ThreadPoolDemo { 7 public static void main(String[] args) throws InterruptedException, 8 ExecutionException { 9 // 創建線程池對象 10 ExecutorService threadPool = Executors.newFixedThreadPool(2); 11 12 // 創建一個Callable接口子類對象
13 // MyCallable c = new MyCallable(); 14 MyCallable c = new MyCallable(100, 200); 15 MyCallable c2 = new MyCallable(10, 20); 16 17 // 獲取線程池中的線程,調用Callable接口子類對象中的call()方法, 完成求和操作 18 // <Integer> Future<Integer> submit(Callable<Integer> task) 19 // Future 結果對象 20 Future<Integer> result = threadPool.submit(c); 21 // 此 Future 的 get 方法所返回的結果類型 22 Integer sum = result.get(); 23 System.out.println("sum=" + sum); 24 25 // 再演示 26 result = threadPool.submit(c2); 27 sum = result.get(); 28 System.out.println("sum=" + sum); 29 // 關閉線程池(可以不關閉) 30 31 } 32 }

3、運行結果:

  技術分享圖片

  

l Callable接口實現類

02027_線程池練習:返回兩個數相加的結果