public class CallableAndFuture { public static void main(String[] args) { Callable
callable = new Callable
() { public Integer call() throws Exception { return new Random().nextInt(100); } }; FutureTask
future = new FutureTask
(callable); new Thread(future).start(); try { Thread.sleep(5000);// 可能做一些事情 System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
public class CallableAndFuture { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future
future = threadPool.submit(new Callable
() { public Integer call() throws Exception { return new Random().nextInt(100); } }); try { Thread.sleep(5000);// 可能做一些事情 System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
public class CallableAndFuture { public static void main(String[] args) { ExecutorService threadPool = Executors.newCachedThreadPool(); CompletionService
cs = new ExecutorCompletionService
(threadPool); for(int i = 1; i < 5; i++) { final int taskID = i; cs.submit(new Callable
() { public Integer call() throws Exception { return taskID; } }); } // 可能做一些事情 for(int i = 1; i < 5; i++) { try { System.out.println(cs.take().get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } }
其实也可以不使用CompletionService,可以先创建一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据,代码略。更新于2016-02-05,评论中就这个说法引发了讨论,其实是我没有讲清楚,抱歉。这里再阐述一下:提交到CompletionService中的Future是按照完成的顺序排列的,这种做法中Future是按照添加的顺序排列的。所以这两种方式的区别就像评论中fishjam所描述的那样。
本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/,转载请注明。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/202824.html原文链接:https://javaforall.net
