CompletionService应用
作者:互联网
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(5);
CompletionService<Integer> cs = new ExecutorCompletionService<>(service);
cs.submit(()->getPriceByS1());
cs.submit(()->getPriceByS2());
cs.submit(()->getPriceByS3());
for (int i = 0; i < 3; i++) {
Integer integer = cs.take().get();
service.execute(() -> save(integer));
}
service.shutdown();
}
public static void save(Integer r){
log.info("保存询价结果:{}",r);
}
public static Integer getPriceByS1() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(5000);
log.info("电商s1的价格1200");
return 1200;
}
public static Integer getPriceByS2() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(8000);
log.info("电商s2的价格1000");
return 1000;
}
public static Integer getPriceByS3() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(3000);
log.info("电商s3的价格800");
return 800;
}
执行结果
标签:service,CompletionService,InterruptedException,static,应用,cs,Integer,public 来源: https://blog.csdn.net/weixin_43861630/article/details/122705931