core线程满负荷且队列也满又有新任务来的时候,会开启临时线程,这个新任务直接到临时线程处理,不进队列,比队列里的后来但是早调度。
在线程池中,当等待队列已满并且有新的任务提交时,一般不是创建临时线程来处理新任务,而是有两种常见的策略:
-
阻塞等待:如果等待队列已满,新提交的任务会被阻塞,直到有空闲线程可用或者有任务被执行完成释放出一个线程资源。这种策略可以确保不会创建额外的线程,而是等待队列中的线程执行完任务后再分配线程去执行新任务。
-
拒绝策略:另一种策略是在等待队列已满时拒绝接受新任务。这可以通过抛出异常或者执行一些其他自定义的操作来实现,以告知调用方无法再接受新任务。这个策略通常用于避免线程池过载,以保护系统的稳定性。
在某些特殊情况下,可能会实现一种临时线程创建策略,但这不是线程池的标准行为。如果使用了这样的策略,那么创建的临时线程通常会用于执行新任务,而不是等待队列中的线程。这可以在特定的应用场景中用来处理突发性的任务负载,但需要格外小心管理临时线程的生命周期和资源消耗。
总的来说,线程池的行为通常由其配置参数和具体实现方式来决定,但在绝大多数情况下,不会创建临时线程来处理等待队列中的任务。相反,会采用阻塞等待或拒绝策略来处理任务的提交。
import java.util.concurrent.*;
public class ThreadPool {
/**
* public ThreadPoolExecutor(int corePoolSize,
* int maximumPoolSize,
* long keepAliveTime,
* TimeUnit unit,
* BlockingQueue<Runnable> workQueue,
* ThreadFactory threadFactory,
* RejectedExecutionHandler handler) {
* if (corePoolSize < 0 ||
* maximumPoolSize <= 0 ||
* maximumPoolSize < corePoolSize ||
* keepAliveTime < 0)
* throw new IllegalArgumentException();
* if (workQueue == null || threadFactory == null || handler == null)
* throw new NullPointerException();
* this.corePoolSize = corePoolSize;
* this.maximumPoolSize = maximumPoolSize;
* this.workQueue = workQueue;
* this.keepAliveTime = unit.toNanos(keepAliveTime);
* this.threadFactory = threadFactory;
* this.handler = handler;
* }
* @param args
*/
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(3,
5,
1L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
executorService.shutdown();
}
}