请问当队列满了之后,线程池会创建线程,那么新创建的线程还是会消费队列头的任务,刚提交的任务进任务队列,还是直接运行刚提交任务?
来源:3-2 增加线程

宝慕林5151746
2020-01-25
写回答
2回答
-
悟空
2020-01-25
直接运行刚提交任务
232021-03-06 -
萨思给
2021-03-06
public class Test { public static void main(String[] args) { ExecutorService executorService = new ThreadPoolExecutor(2, 5, 0, TimeUnit.DAYS, new ArrayBlockingQueue<>(2), new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); return thread; } }); executorService.execute(() -> { System.out.println("任务1@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); executorService.execute(() -> { System.out.println("任务2@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); executorService.execute(() -> { System.out.println("任务3@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); executorService.execute(() -> { System.out.println("任务4@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); executorService.execute(() -> { System.out.println("任务5@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); executorService.execute(() -> { System.out.println("任务6@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); executorService.execute(() -> { System.out.println("任务7@" + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { } }); } 一个运行结果是 任务1@Thread-0 任务2@Thread-1 任务5@Thread-2 任务6@Thread-3 任务7@Thread-4 任务3@Thread-1 任务4@Thread-4 任务5,6, 7比任务3,4运行的早,看起来3和4都是被加到队列里了,队列满了后,新进来的任务(5,6,7)是直接创建线程执行的,然后再从队列头开始执行
012021-03-07
相似问题