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 有問題");
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM