java同步例子之FutureTask
程序员文章站
2022-04-21 09:27:13
...
仅在计算完成时才能获取结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算.
package concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * FutureTask * * @author user * */ public class FutureTaskTest { private final FutureTask<ProductInfo> future = new FutureTask<ProductInfo>( new Callable<ProductInfo>() { public ProductInfo call() throws InterruptedException { return loadProductInfo(); } }); public ProductInfo loadProductInfo() throws InterruptedException { System.err.println("=====waiting========"); Thread.sleep(5000); return new ProductInfo(); } private final Thread thread = new Thread(future); public void start() { thread.start(); } public ProductInfo get() throws InterruptedException, ExecutionException, TimeoutException { try{ return future.get(1, TimeUnit.SECONDS); } catch(TimeoutException e) { //future.cancel(true); //取消任务 System.err.println("火速返回,失败!"); return future.get(10, TimeUnit.SECONDS); } } /** * @param args * @throws ExecutionException * @throws InterruptedException * @throws TimeoutException */ public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { FutureTaskTest test = new FutureTaskTest(); test.start(); System.err.println("=======begin========"); System.err.println(test.get()); System.err.println("=======end========"); } } class ProductInfo { public String toString() { return "**ProductInfo**"; } }