控制线程同时运行数量

package com.dwz.concurrency.chapter9;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

public class CaptureService {
    private final static LinkedList<Control> CONTROLS = new LinkedList<>();
    private final static int MAX_WORKER = 5;
    
    private static Thread createCaptureThread(String name) {
        return new Thread(() -> {
            Optional.of("The worker ["+Thread.currentThread().getName()+"] begin capture data").ifPresent(System.out::println);
            synchronized (CONTROLS) {
                while (CONTROLS.size() >= MAX_WORKER) {
                    try {
                        CONTROLS.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                CONTROLS.addLast(new Control());
            }
            
            Optional.of("The worker ["+Thread.currentThread().getName()+"] is working..").ifPresent(System.out::println);
            try {
                Thread.sleep(10_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            synchronized (CONTROLS) {
                Optional.of("The worker ["+Thread.currentThread().getName()+"] End capture data.., CONTROLS size is "+CONTROLS.size()).ifPresent(System.out::println);
                CONTROLS.removeFirst();
                CONTROLS.notifyAll();
            }
        }, name) ;
    }
    public static void main(String[] args) {
        List<Thread> worker = new ArrayList<>();
        Arrays.asList("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10", "M11", "M12", "M13")
                .stream()
                .map(CaptureService :: createCaptureThread)
                .forEach(t -> {
                    t.start();
                    worker.add(t);
                });
        worker.stream().forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        Optional.of("All of capture work finished").ifPresent(System.out::println);
    }
    
    private static class Control {}
}

测试结果,同一时间里实际上始终最多有5个线程同时运行

上一篇:后台


下一篇:C#-单击下拉菜单的箭头/下拉菜单的延迟加载,加载下拉列表