Java線程池使用AbortPolicy策略

線程池ThreadPoolExecutor的拒絕策略

線程池中的線程資源全部被占用時,對新添加的Task任務有不同的處理策略,在默認的情況下,

ThreadPoolExecutor類中有4種不同的處理方式:

  • AbortPolicy:當任務添加到線程池中被拒絕時,它將拋出RejectExecutionException異常。
  • CallerRunsPolicy:當任務添加到線程池中被拒絕時,會使用調用線程池的Thread線程對象處理被拒絕的任務。
  • DiscardOldestPolicy: 當任務添加到線程池中被拒絕時,線程池會放棄等待隊列中最舊的未處理任務,然後將被拒絕的任務添加到等待隊列中。
  • DiscardPolicy:當任務添加到線程池中被拒絕時,線程池將丟棄被拒絕的任務。

AbortPolicy策略

AbortPolicy策略是當任務添加到線程池中被拒絕時,它將拋出RejectedExecutionException異常。

線程執行代碼如下:

public class FirstRunnable implements Runnable {
    @Override
    public void run() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        try {
            System.out.println(Thread.currentThread().getName() +"  開始時間:"+simpleDateFormat.format(new Date()));
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +"  結束時間:"+simpleDateFormat.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

運行類代碼如下:

public class AbortPolicyRun {
    public static void main(String[] args) {
        FirstRunnable firstRunnable = new FirstRunnable();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 7 ; i++) {
            threadPoolExecutor.execute(firstRunnable);
        }
    }
}

運行結果如下:

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.ozx.concurrentprogram.executor.service.FirstRunnable@6c629d6e rejected from java.util.concurrent.ThreadPoolExecutor@5f5a92bb[Running, pool size = 3, active threads = 3, queued tasks = 2, completed tasks = 0]
    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
    at com.ozx.concurrentprogram.executor.controller.AbortPolicyRun.main(AbortPolicyRun.java:19)
pool-1-thread-3  開始時間:16:20:27
pool-1-thread-1  開始時間:16:20:27
pool-1-thread-2  開始時間:16:20:27
pool-1-thread-2  結束時間:16:20:28
pool-1-thread-2  開始時間:16:20:28
pool-1-thread-1  結束時間:16:20:28
pool-1-thread-1  開始時間:16:20:28
pool-1-thread-3  結束時間:16:20:28
pool-1-thread-1  結束時間:16:20:29
pool-1-thread-2  結束時間:16:20:29

使用AbortPolicy策略後,線程任務數量超出線程池最大線程數時,線程池將拋出java.util.concurrent.RejectedExecutionException異常。

到此這篇關於 Java線程池使用AbortPolicy策略的文章就介紹到這瞭,更多相關Java AbortPolicy內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: