最近遇到一个需求,其中一个操作比较耗时。为了提高效率,我选择新开线程异步去做。由于需要对方法的返回值进行操作,我选择使用FutureTask,可以循环获取task,并调用get方法去获取task执行结果,但是如果task还未完成,获取结果的线程将阻塞直到task完成。后来发现了CompletionService类,它整合了Executor和BlockingQueue的功能。可以将Callable任务提交给它去执行,然后使用类似于队列中的 take 方法获取线程的返回值。
demo 如下:
package com.aliyun.callback;
import org.junit.Test;
import java.util.Random;
import java.util.concurrent.*;
/**
* Created by Demon, on 2018/4/25
*/
public class CompletionServiceTest {
private static final int DEFAULT_CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() <= 1 ? 2 :
Runtime.getRuntime().availableProcessors() * 2;
private static final int DEFAULT_MAXNUM_POOL_SIZE = 32;
private static final int DEFAULT_KEEP_ALIVE_TIME = 30;
private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXNUM_POOL_SIZE
, DEFAULT_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20));
@Test
public void test() {
CompletionService<String> completionService = new ExecutorCompletionService<>(threadPool);
try {
for (int i = 0; i < 5; i++) {
Task task = new Task("threadName" + i);
// 使用submit 主线程可以捕捉到异步线程中的异常
completionService.submit(task);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
try {
Future<String> future = completionService.take();
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
private class Task implements Callable<String> {
private String name;
private Task(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
int sleepTime = new Random().nextInt(1000);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 返回给调用者的值
String str = name + " sleep time:" + sleepTime;
System.out.println(name + " finished...");
// throw new RuntimeException("test catch error");
return str;
}
}
}
运行结果:
threadName0 finished...
threadName0 sleep time:140
threadName4 finished...
threadName4 sleep time:250
threadName3 finished...
threadName3 sleep time:258
threadName1 finished...
threadName1 sleep time:416
threadName2 finished...
threadName2 sleep time:712
使用CompletionService来维护处理线程的返回结果时,主线程总是能够拿到最先完成的任务的返回值,而不管它们加入线程池的顺序, 这样就可以减少主线程阻塞时间,优于原生的 future.get方法。