You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Runnable实现固定5个并发线程,线程结束后启动新线程如何实现?

实现方案

核心思路

使用JDK自带的java.util.concurrent.Semaphore(信号量)做并发数控制,指定5个许可,同一时间仅允许5个线程拿到许可执行业务逻辑,线程执行完毕后释放许可供后续线程使用,完全符合你要求的保留Runnable、保留new Thread(xxx).start()调用的限制。

改造后代码

import java.util.concurrent.Semaphore;
import java.math.BigDecimal;

// 你的原有类逻辑
public class Controller {
    // 省略logger定义等原有代码

    public void testThread() throws InterruptedException {
        // 定义信号量,许可数为5,保证同时最多5个线程运行
        Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 20; i++) {
            BigDecimal threadNumber = new BigDecimal(i);

            Runnable r = () -> {
                try {
                    // 先获取许可,拿不到就阻塞等待
                    semaphore.acquire();
                    
                    logger.info("thread execution started.");
                    try {
                        Thread.sleep(1000 * 30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    logger.info("thread execution ended.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                } finally {
                    // 必须在finally里释放许可,避免异常导致许可泄漏
                    semaphore.release();
                }
            };
            // 完全保留你原有的线程启动调用方式
            new Thread(r, "thread-nb-" + threadNumber).start();
        }
    }
}

效果说明

运行代码后控制台只会先打印5条thread execution started.日志,30秒后第一批线程陆续执行结束释放许可,才会有新的线程拿到许可启动打印启动日志,全程同时运行的线程数不会超过5个,完全符合需求。


内容的提问来源于stack exchange,提问作者electrode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:30:04