corePoolSize

来源:3-5 用法演示

慕用6288624

2021-03-07

package threadpool;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolTest {
    public static void main(String[] args) {
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);

        // 第一个参数是任务,第二个参数是延时多长时间执行,第三个参数是时间单位
        //threadPool.schedule(new Task(), 5, TimeUnit.SECONDS);

        // 一开始隔1s执行一次,之后隔3s
        threadPool.scheduleAtFixedRate(new Task(), 1, 3, TimeUnit.SECONDS);
    }
}

图片描述

老师不是说如果线程数小于corePoolSize,即使其他工作线程处于空闲状态,也会创建一个新线程来执行任务吗?如代码所示,创建了一个线程,然后Task任务是睡眠500ms,线程池是隔3s才新建一个线程,corePoolSize是10。线程1执行完了任务进入空闲,那再次创建线程的时候不是应该创建新线程去执行Task任务吗?为啥还会反复的用pool-1-thread-1线程,此时线程数是少于corePoolSize的啊

写回答

1回答

悟空

2021-03-08

很好的问题,课程里分析的是ThreadPoolExecutor的execute方法,我测试了:

public class ScheduledThreadPoolTest {

   public static void main(String[] args) {
       ExecutorService threadPool = Executors.newFixedThreadPool(10);

       for (int i = 0; i < 10; i++) {
           threadPool.execute(new Task());
           try {
               Thread.sleep(1000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

   }

   static class Task implements Runnable {


       @Override
       public void run() {
           System.out.println(Thread.currentThread().getName());
       }
   }
}

输出结果:

pool-1-thread-1

pool-1-thread-2

pool-1-thread-3

pool-1-thread-4

pool-1-thread-5

pool-1-thread-6

pool-1-thread-7

pool-1-thread-8

pool-1-thread-9

pool-1-thread-10


都是新建线程来执行新任务的。

0
1
慕用6288624
非常感谢!
2021-03-09
共1条回复

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程