在前一篇博客中介绍了多线程在Groovy中的应用,发现Future获取结果的时候会阻塞,不能做到真正意义上的异步编程,之后再整理对应的原理解析篇,这里就先贴它的使用方式,因为公司代码不方便贴出来,所以贴了个简单的示例代码。
import java.util.stream.Collectors
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.BlockingQueue;
import com.zqlian.common.base.PluginResult;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 同步获取异步执行结果
*/
ArrayBlockingQueue queue2 = new ArrayBlockingQueue<Runnable>(10000);
ExecutorService tPool = new ThreadPoolExecutor(50, 500, 20, TimeUnit.SECONDS, queue2);
CopyOnWriteArrayList<CompletableFuture<HashMap>> futures = new CopyOnWriteArrayList<CompletableFuture<HashMap>>();
for (int i = 0; i < 4; i++) {
futures.add(CompletableFuture.supplyAsync({
HashMap item = new HashMap();
item.put("hhh", "ddd");
return item;
}, tPool));
}
CompletableFuture<Void> allCompletableFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
List<HashMap> join = allCompletableFuture.thenApply({
return futures.stream()
.map({
return it.join();
}).collect(Collectors.toList());
}).join();
return PluginResult.ok(join);
执行结果
{
"result": 0,
"message": "ok",
"data": [
{
"hhh": "ddd"
},
{
"hhh": "ddd"
},
{
"hhh": "ddd"
},
{
"hhh": "ddd"
}
]
}