package com;
import java.math.BigDecimal;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* ExecutorCompletionService示例,用线程池执行2个运行结果
* @author Administrator
*
*/
public class ExecutorCompletionServiceDemo {
public static void main(String[] args) throws Exception {
ExecutorService executor=Executors.newFixedThreadPool(2);
Callable<BigDecimal> callabe1=() -> {
Thread.sleep(500);
return new BigDecimal("1");
};
Callable<BigDecimal> callabe2=() -> {
Thread.sleep(500);
return new BigDecimal("2");
};
ExecutorCompletionService<BigDecimal> ecs = new ExecutorCompletionService<BigDecimal>(executor);
ecs.submit(callabe1);
ecs.submit(callabe2);
//结果的顺序是不定的
System.out.println(ecs.take().get());//take是没有结果就一直等待
System.out.println(ecs.poll().get());//poll是没有结果就报null
executor.shutdown();
}
}
运行结果