相比ExecutorService,CompletionService可以更精确和简便地完成异步任务的执行 CompletionService的一个实现是ExecutorCompletionService,它是Executor和BlockingQueue功能的融合体,Executor完成计算任务,BlockingQueue负责保存异步任务的执行结果 在执行大量相互独立和同构的任务时,可以使用CompletionService CompletionService可以为任务的执行设置时限,主要是通过BlockingQueue的poll(long time,TimeUnit unit)为任务执行结果的取得限制时间,如果没有完成就取消任务
package com.xxx.utils; import com.alibaba.fastjson.JSONObject; import com.xxx.IomsApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.concurrent.*; @SpringBootTest(classes = xxxApplication.class) @RunWith(SpringRunner.class) public class CompletionDemo { @Autowired @Qualifier("serviceThreadPool") private Executor executor; @Test public void getCompletion(){ ExecutorCompletionService<Object> executorCompletionService = new ExecutorCompletionService<>(executor); //方式1 executorCompletionService.submit( new Callable<Object>() { @Override public Object call() throws Exception { String str = "qwe"; return str; } } ); //方式2 executorCompletionService.submit(()->{ String str = "qwe"; return str; }); try { Object o = executorCompletionService.take().get(); System.out.println(o);//输出;qwe } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } @Test public void futureTask(){ //futureTaskClass可传入参name,亦可不传参数 //下面的JSONObject是返回类型,根据要求设置 String name = "qwe"; //方式1 FutureTask<JSONObject> futureTask = new FutureTask<>(new futureTaskClass(name)); //方式2 FutureTask<JSONObject> futureTask1 = new FutureTask<>(()->{ JSONObject jsonObject = new JSONObject(); jsonObject.put("qq","qwe"); return jsonObject; }); executor.execute(futureTask); try { JSONObject jsonObject = futureTask.get(); System.out.println(jsonObject);//输出:{"qq":"qwe"} } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } public class futureTaskClass implements Callable<JSONObject> { private String name ; public futureTaskClass(String name) { this.name = name; } @Override public JSONObject call() throws Exception { //做业务处理 //do something JSONObject jsonObject = new JSONObject(); jsonObject.put("qq","qwe"); return jsonObject; } } } 可参考:
多线程之ExecutorCompletionService使用_一 路的博客-CSDN博客_executorcompletionservice