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回答
-
很好的问题,课程里分析的是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
都是新建线程来执行新任务的。
012021-03-09
相似问题