使用CompletionService解决Future的get方法阻塞问题
解决方法:
CompletionService 的take()方法获取最先执行完的线程的Future对象。
1.测试方法
public static void main(String[] args) throws Exception {
CallableDemo callable = new CallableDemo(1,100000);
CallableDemo callable2 = new CallableDemo(1,100);
ThreadPoolExecutor executor = new
ThreadPoolExecutor(4, 5, 5L,
TimeUnit.SECONDS, new LinkedBlockingDeque());
CompletionService csRef = new ExecutorCompletionService(executor);
System.out.println("main 1 " +System.currentTimeMillis());
csRef.submit(callable);
csRef.submit(callable2);
System.out.println("main 2 " +System.currentTimeMillis());
System.out.println(csRef.take().get());
System.out.println("main 3 " +System.currentTimeMillis());
System.out.println(csRef.take().get());
System.out.println("main 4 " +System.currentTimeMillis());
}
2.线程类
import java.util.concurrent.Callable;
public class CallableDemo implements Callable<String> {
private int begin;
private int end;
private int sum;
public CallableDemo(int begin, int end) {
super();
this.begin = begin;
this.end = end;
}
public String call() throws Exception {
for(int i=begin;i<=end;i++){
for(int j=begin;j<=end;j++){
sum+=j;
}
}
Thread.sleep(8000);
return begin+"-" +end+"的和:"+ sum;
}
}
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1546