标签:返回结果 throw tool target led get load 返回 row
默认的异步任务有些难以控制,有时候我们希望在当前线程获取异步任务的结果。FutureTask可以帮助我们实现
JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/FutureTask.html
以下代码,我们创建了FutureTask实例,然后将它丢给一个线程去执行。
再调用get方法阻塞等待异步结果,异步线程执行futureTask以后,返回结果。get方法获取结果以后,停止阻塞状态,打印结果。
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class FutureTaskDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<String> futureTask = new FutureTask<>(() -> { System.out.println("future task is called"); Thread.sleep(2000); return "futureTask is done"; }); new Thread(futureTask).start(); System.out.println(futureTask.get()); } }
标签:返回结果 throw tool target led get load 返回 row
原文地址:https://www.cnblogs.com/lay2017/p/10165515.html