进阶day06-线程池:处理Callable任务
This commit is contained in:
28
javaSE-day06/src/com/inmind/thread_pool10/Demo13.java
Normal file
28
javaSE-day06/src/com/inmind/thread_pool10/Demo13.java
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package com.inmind.thread_pool10;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
/*
|
||||||
|
学习任务:线程池:处理Callable任务
|
||||||
|
|
||||||
|
提交Callable任务的API:
|
||||||
|
<T> Future<T> submit(Callable<T> task) 提交值返回任务以执行,并返回代表任务待处理结果的Future。
|
||||||
|
|
||||||
|
注意:有返回的子线程操作,它的返回值会封装在Future中,通过get方法来获取
|
||||||
|
*/
|
||||||
|
public class Demo13 {
|
||||||
|
public static void main(String[] args) throws ExecutionException, InterruptedException {
|
||||||
|
//创建线程池
|
||||||
|
ExecutorService threadPool = Executors.newFixedThreadPool(5);
|
||||||
|
Future<Integer> future1 = threadPool.submit(new MyCallable(5));
|
||||||
|
Future<Integer> future2 = threadPool.submit(new MyCallable(3));
|
||||||
|
Future<Integer> future3 = threadPool.submit(new MyCallable(10));
|
||||||
|
|
||||||
|
System.out.println("任务1返回的结果为:"+future1.get());
|
||||||
|
System.out.println("任务2返回的结果为:"+future2.get());
|
||||||
|
System.out.println("任务3返回的结果为:"+future3.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
25
javaSE-day06/src/com/inmind/thread_pool10/MyCallable.java
Normal file
25
javaSE-day06/src/com/inmind/thread_pool10/MyCallable.java
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package com.inmind.thread_pool10;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
|
||||||
|
public class MyCallable implements Callable<Integer> {
|
||||||
|
int sum = 0;
|
||||||
|
|
||||||
|
public MyCallable(int sum) {
|
||||||
|
this.sum = sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
//计算固定值的累和
|
||||||
|
@Override
|
||||||
|
public Integer call() throws Exception {
|
||||||
|
//计算sum的累和
|
||||||
|
int result = 0;
|
||||||
|
for (int i = 0; i <= sum; i++) {
|
||||||
|
result+= i;
|
||||||
|
}
|
||||||
|
Thread.sleep(1000);
|
||||||
|
System.out.println(Thread.currentThread().getName()+"执行完累加操作,结果为:"+result);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user