当前位置: 首页>后端>正文

CountDownLatch门栓

一,简单demo样例

package cn.codeduck.multi;

import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountDownLatchTest {

    private ExecutorService taskExecutorService = new ThreadPoolExecutor(20, 40, 100, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     *
     */
    @Test
    public String test01(){
        // 生成参数集合
        List<Integer> paramList = Stream.iterate(1, val -> val + 1).limit(20).collect(Collectors.toList());
        System.out.println(paramList);

        // 定义门栓多线程执行
        CountDownLatch latch = new CountDownLatch(paramList.size());
        for (Integer val : paramList) {
            taskExecutorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(val);
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        String result = null;
        try {
            // 等待所有线程执行完成
            boolean isFinished = latch.await(2000, TimeUnit.MILLISECONDS);
            if (isFinished){
                // success
                result = "success";
            }else {
                // fail
                result = "fail" + JSON.toJSONString(paramList);
            }
        } catch (InterruptedException e) {
            // exception
            result = "exception";
        }

        // 返回结果
        return result;
    }

}

更多参考:
如何让主线程等待所有的子线程结束之后再执行


https://www.xamrdz.com/backend/3ce1994522.html

相关文章: