在Java中,ThreadPoolExecutor
提供了四種內置的拒絕策略,分別是:
RejectedExecutionException
異常。要設置拒絕策略,需要創建一個ThreadPoolExecutor
實例,并在構造函數中傳入相應的策略。以下是一個使用CallerRunsPolicy
拒絕策略的示例:
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
int corePoolSize = 2;
int maximumPoolSize = 4;
long keepAliveTime = 10L;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(3);
// 設置拒絕策略為 CallerRunsPolicy
RejectedExecutionHandler rejectionPolicy = new CallerRunsPolicy();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
rejectionPolicy
);
for (int i = 0; i < 10; i++) {
int finalI = i;
threadPoolExecutor.submit(() -> {
System.out.println("Task " + finalI + " is running on thread " + Thread.currentThread().getName());
});
}
threadPoolExecutor.shutdown();
}
}
在這個示例中,我們創建了一個ThreadPoolExecutor
實例,并設置了CallerRunsPolicy
作為拒絕策略。然后我們提交了10個任務到線程池中,當任務數量超過線程池的處理能力時,將會使用CallerRunsPolicy
策略處理無法被接受的任務。