JAVA 1.5 并发之 Executor框架 (二)execute VS submit

http://www.cnblogs.com/rockman12352/p/3788688.html

上一篇对于整体框架讲了很多东西,但是具体在使用时有一些细节并没有说出来

 

首先是执行任务

execute(); 执行任务,返回空,相当于 new Thread(task).start();

submit();   执行任务,但是会返回一个future<T>,就是计算好的结果,如果没有计算好则会阻塞,还有一个好处是可以管理exception

 

public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        CompletionService<Integer> comp = new ExecutorCompletionService<Integer>(executor);

        Callable<Integer> task1 = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(50);
                return 1;
            }
        };

        Callable<Integer> task2 = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(100);
                throw new Exception("test");
            }
        };

        Future<Integer> future1 = comp.submit(task1);
        Future<Integer> future2 = comp.submit(task2);

        try {
            System.out.println(comp.take().get());
            System.out.println(comp.take().get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        executor.shutdown();
    }

  第一个task输出1

  第二个task输出exception

 

然后再讲讲关闭

shutdown(); 禁止继续接新任务,但是已经接了的会执行下去

shutdownNow();立即停止所有任务,也禁止接任务

    原文作者:rockman12352
    原文地址: http://www.cnblogs.com/rockman12352/p/3789275.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞