CallableFuture

代码:

public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();// submit是提交以便返回结果Future<String> future = threadPool.submit(new Callable<String>() {public String call() throws Exception {Thread.sleep(2000);return "hello";};});System.out.println("等待结果");try {System.out.println("拿到结果:" + future.get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

结果:

Executor使我们无需显示的去管理线程的生命周期。

2、执行多个带返回值的任务,并取得多个返回值

//方式2 CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象//好比我同时种了几块地的麦子,然后就等待收割。收割时,则是那块先成熟了,则先去收割哪块麦子。ExecutorService threadPool2 = Executors.newFixedThreadPool(10);CompletionService<Integer> compeletionService = new ExecutorCompletionService<Integer>(threadPool2);for (int i = 0; i <= 10; i++) {final int seq = i;compeletionService.submit(new Callable<Integer>() {@Overridepublic Integer call() throws Exception {Thread.sleep(new Random().nextInt(5000));return seq;}});}for (int i = 0; i < 10; i++) {try {//产生线程,,返回结果再把结果拿回来System.out.println(compeletionService.take().get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

结果:

3、了解Callable接口以及Future接口

版权声明:本文为博主原创文章,未经博主允许不得转载。

可是我知道结果是惨淡的,但还是心存希望!

CallableFuture

相关文章:

你感兴趣的文章:

标签云: