线程控制

1. AtomicInteger  线程安全的计数器, 可以用于控制当前执行的线程数
// 类上定义
public static AtomicInteger runningSize = new AtomicInteger(0);
private static ExecutorService threadPool = Executors.newFixedThreadPool(maxRunningApplications);
// 方法中启动死循环的线程
while(true) {
    // 判断是否打满,如果打满就一直等待,5分钟看一次好了才放行   
    while(runningSize>=最大线程数) {
        thread.sleep(5000);    
     }
     runningSize.incrementAndGet(); // +1
     threadPool.execute(new Runnalbe() {
         public void run() {
             // todo 你的业务
             // 业务执行完后 -1
             runningSize.decrementAndGet();
          }
     });
                 
}    

 

2. 控制线程组完成 CountDownLatch

List<Data> dataList = getData(); // 获取数据
ExecutorService threadPool = Executors.newFixedThreadPool(10);

// 创建倒数计数器
CountDownLatch latch = new CountDownLatch(dataList.size());

for (Data data : dataList) {
    threadPool.submit(() -> {
        try {
            // 处理数据
            process(data);
        } finally {
            // 每完成一个任务,计数减一
            latch.countDown();
        }
    });
}

// 【关键】主线程阻塞,直到latch计数为0
latch.await();

// 所有任务完成,执行统计
otherthings();

threadPool.shutdown();

  

posted @ 2025-10-23 11:28  trump2  阅读(1)  评论(0)    收藏  举报