【发布时间】:2021-11-07 23:56:43
【问题描述】:
我有这样的代码,使用 Runnable :
for (int i = 0; i < 20; i++) {
BigDecimal threadNumber = new BigDecimal(i);
Runnable r = () -> {
logger.info("thread execution started.");
try {
Thread.sleep(1000 * 30);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("thread execution ended.");
};
new Thread(r, "thread-nb-" + threadNumber).start();
}
它完美地工作并同时启动。控制台显示:
2021-09-12 10:58:48,819 INFO [thread-nb-0] com.Controller: thread execution started.
2021-09-12 10:58:48,819 INFO [thread-nb-1] com.Controller: thread execution started.
2021-09-12 10:58:48,819 INFO [thread-nb-2] com.Controller: thread execution started.
..
2021-09-12 10:58:48,819 INFO [thread-nb-18] com.Controller: thread execution started.
2021-09-12 10:58:48,819 INFO [thread-nb-29] com.Controller: thread execution started.
但是,我现在想做的是一次只触发 5 个第一个线程, 一旦 5 个第一个结束,第 6 个将开始。 如何做到这一点,保持 Runnable 和 new Thread(xxx).start(); 的使用?
提前致谢
【问题讨论】:
-
您可以使用 线程池 做到这一点。 Eugen Paraschiv 写了一个非常好的Introduction to Thread Pools in Java。
-
另外,您可以使用a Semaphore class。本质上,您可以设置可以锁定信号量的线程限制(如 5 个),然后其余线程等待新的可用限制。我不建议在生产代码中这样做。
标签: java multithreading runnable