02027_线程池练习:返回两个数相加的结果
生活随笔
收集整理的這篇文章主要介紹了
02027_线程池练习:返回两个数相加的结果
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、要求:通過線程池中的線程對象,使用Callable接口完成兩個數(shù)求和操作。
2、代碼實現(xiàn):
(1)Callable接口實現(xiàn)類
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 // 構(gòu)造方法 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 // 創(chuàng)建線程池對象 10 ExecutorService threadPool = Executors.newFixedThreadPool(2); 11 12 // 創(chuàng)建一個Callable接口子類對象 13 // MyCallable c = new MyCallable(); 14 MyCallable c = new MyCallable(100, 200); 15 MyCallable c2 = new MyCallable(10, 20); 16 17 // 獲取線程池中的線程,調(diào)用Callable接口子類對象中的call()方法, 完成求和操作 18 // <Integer> Future<Integer> submit(Callable<Integer> task) 19 // Future 結(jié)果對象 20 Future<Integer> result = threadPool.submit(c); 21 // 此 Future 的 get 方法所返回的結(jié)果類型 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 // 關(guān)閉線程池(可以不關(guān)閉) 30 31 } 32 }3、運行結(jié)果:
?
l? Callable接口實現(xiàn)類
?
轉(zhuǎn)載于:https://www.cnblogs.com/gzdlh/p/8099279.html
總結(jié)
以上是生活随笔為你收集整理的02027_线程池练习:返回两个数相加的结果的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go语言中将函数作为变量传递
- 下一篇: F. 配置多站点