package com.main.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableAndFuture {
public static void main(String[] args) throws Exception {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
//1.提交一个任务
Future<String> future = threadPool.submit(new Callable<String>(){
//callable任务可以返回结果
@Override
public String call() throws Exception {
return "hello";
}
});
System.out.println(future.get()+"============");//这种方式必须要等 future取结果
//2.提交一组Callable任务 返回任务完成的结果
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
for(int j=0;j<10;j++){
final int task = j;
cs.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return task;
}
});
}
for(int i=0;i<10;i++){
System.out.println(cs.take().get());
}
}
}
@Test
public void test41() throws Exception{
ExecutorService threadPool = Executors.newCachedThreadPool();
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
for(int j=0;j<100;j++){
final int task = j;
cs.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("======="+task);
return task;
}
});
}
threadPool.shutdown();
for(int j=0;j<100;j++){
cs.take().get(); //阻塞方法 只有这个任务完成下个动作才执行
}
System.out.println("andy yuan");
}