在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
策略处理无法被接受的任务。