ThreadPoolExecutor出现异常的处理方法

ThreadPoolExecutor出现异常的处理方法

共4种:引用huaxiao

import java.util.concurrent.*;

public class ExceptionTest {
    public static void main(String[] args) {
        ExceptionTest test = new ExceptionTest();
        test.method1();
        test.method2();
        test.method3();
        test.method4();
    }

    /**
     * try catch捕获
     */
    public void method1(){
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            threadPool.submit(() -> {
                System.out.println("current thread name" + Thread.currentThread().getName());
                try{
                    Object object = null;
                    System.out.print("result## "+object.toString());
                }catch (Exception e){
                    System.out.println("method1有异常");
                }
            });
        }
    }

    /**
     * future.get接收异常  这个方法是会得到返回值,得不到则失败
     */
    public void method2(){
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            Future future = threadPool.submit(() -> {
                System.out.println("current thread name" + Thread.currentThread().getName());

                Object object = null;
                System.out.print("result## " + object.toString());
            });

            try{
                future.get();
            }catch(Exception e){
                System.out.println("method2发生异常");
            }
        }
    }

    /**
     * 自定义线程工厂,然后设置UncaughtExceptionHandler
     */
    public void method3(){
        ExecutorService threadPool = Executors.newFixedThreadPool(1, r -> {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler(
                    (t1, e) -> {
                        System.out.println(t1.getName() + " method3 线程抛出的异常"+e);
                    });
            return t;
        });

        threadPool.execute(()->{
            Object object = null;
            System.out.print("result## " + object.toString());
        });
    }


    /**
     * 复写ThreadPoolExecutor 的afterExecute方法,处理异常
     */
    public void method4(){
        ExecutorService threadPool = new ExtendedExecutor(1,5,10,TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        //4中默认拒绝策略,直接调用即可。Abort抛异常,Discard扔掉,DiscardOldest扔掉队列中最久的,CallerRuns谁调用我,谁来处理这个任务
        threadPool.execute(()->{
            Object object = null;
            System.out.print("result## " + object.toString());
        });
    }

}

class ExtendedExecutor extends ThreadPoolExecutor {

    public ExtendedExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public ExtendedExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    // 这可是jdk文档里面给的例子。。
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);  //先继承父类方法
        if (t == null && r instanceof Future<?>) {
            try {
                Object result = ((Future<?>) r).get();
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt(); // ignore/reset
            }
        }
        if (t != null)  //处理异常的地方
            System.out.println("method4 有问题");
    }
}
posted @ 2020-06-18 09:34  Muche  阅读(2029)  评论(0)    收藏  举报