控制线程同时运行数量

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个线程同时运行

posted @ 2019-12-19 13:59  龙宇在天  阅读(502)  评论(0编辑  收藏  举报
//右侧添加目录 //增加页面点击显示24字社会主义核心价值观