JDK1.5 获取线程履行成果 Callable FutureITeyefenghuang - AG环亚娱乐

JDK1.5 获取线程履行成果 Callable FutureITeyefenghuang

2019-01-31 11:43:36 | 作者: 雅青 | 标签: 成果,线程,等候 | 浏览: 5801

import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; * Callable Future (类是有回调的 线程池使命) 能够获取 线程履行后的 成果(无序的) public class CallableAndFuture { * @param args * @throws ExecutionException * @throws InterruptedException public static void main(String[] args) throws InterruptedException,Exception { ExecutorService threadPool=Executors.newSingleThreadExecutor(); // 提交当个使命 然后获取等候成果 Future String future=threadPool.submit(new Callable String () { @Override public String call() throws Exception { // TODO Auto-generated method stub Thread.sleep(2000); return "Hello: "+Thread.currentThread().getName(); System.out.println("等候成果中..."); //什么时候有成果后 再获取成果 System.out.println("成果为:"+future.get()); //等候 1秒后 获取成果 没有取到成果就算了 System.out.println("成果为:"+future.get(1, TimeUnit.SECONDS)); threadPool.shutdown(); //批量提交使命 然后 循环获取 履行后的成果 ExecutorService threadPool1=Executors.newFixedThreadPool(10); CompletionService Integer completionService=new ExecutorCompletionService Integer (threadPool1); for (int i = 0; i i++) { final int seq=i; completionService.submit(new Callable Integer () { @Override public Integer call() throws Exception { // TODO Auto-generated method stub Thread.sleep(new Random().nextInt(5000)); return seq; System.out.println("2等候成果中..."); for (int i = 0; i i++) { System.out.println(completionService.take().get()); threadPool1.shutdown();
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表AG环亚娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章