码迷,mamicode.com
首页 > 编程语言 > 详细

Java 并发:Executor

时间:2015-03-07 22:30:36      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

 

异常捕获

以前使用executor的时候,为了记录任务线程的异常退出会使用ThreadFactory来设置线程的UncaughtExceptionHandler,但是按照书上的验证发现,采用executorService.submit执行任务时,线程抛出的异常并不会被该处理器捕获,而当使用executor.execute提交任务时则会被捕获。代码如下:

        final UncaughtExceptionHandler handler = new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(final Thread t, final Throwable e) {
                System.out.println("uncaught exception");
            }
        };

        ThreadFactory exFactory = new ThreadFactory() {
            @Override
            public Thread newThread(final Runnable r) {
                Thread x = new Thread(r);
                x.setUncaughtExceptionHandler(handler);
                return x;
            }
        };

        ExecutorService es = Executors.newSingleThreadExecutor(exFactory);
     // es.execute(new Runnable() { es.submit(
new Runnable() { @Override public void run() { ArrayList<Integer> x = new ArrayList<Integer>(); System.out.println(x.get(10)); // index out of bound } });

如果要获得submit任务的异常需要使用其返回的future对象,执行器get方法如下:

        ExecutorService es = Executors.newSingleThreadExecutor(exFactory);
        Future<Void> f = (Future<Void>) es.submit(new Runnable() {
            @Override
            public void run() {
                ArrayList<Integer> x = new ArrayList<Integer>();
                System.out.println(x.get(10));
            }
        });

        try {
            f.get();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ExecutionException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

此时程序会打印错误信息。

Java 并发:Executor

标签:

原文地址:http://www.cnblogs.com/lailailai/p/4320999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!