线程池处理异常方案

内容纲要

1. try-catch

    static ExecutorService threadPool = new ThreadPoolExecutor(
            2,5,1L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(3),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        threadPool.execute(()->{
            try {
                int i = 10/0;
            }catch (Exception e){
                e.printStackTrace();
            }
        });
    }

2线程工程

    static ExecutorService threadPool = new ThreadPoolExecutor(
            2, 5, 1L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(3),
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable runnable) {
                    Thread thread = new Thread(runnable);
                    thread.setUncaughtExceptionHandler((t, e) -> {
                        System.out.println("异常情况 : " + e.getMessage() + "\t " + e);
                    });
                    return thread;
                }
            },
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        threadPool.execute(() -> {
                int i = 10 / 0;
        });
    }
THE END
分享
二维码
< <上一篇
下一篇>>