美文网首页
CountDownLatch的应用

CountDownLatch的应用

作者: 知道越多不知道越多 | 来源:发表于2018-11-13 19:44 被阅读0次

使用场景,在多线程执行完成后根据多线程执行返回值继续后续操作。
代码如下

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class ThreadPoolDemo {

private final static ExecutorService executor = Executors.newFixedThreadPool(10);

public static void main(String[] args) {
    
    final List<Integer> resultList = Collections.synchronizedList(new ArrayList<Integer>());
    int num = 100;
    final CountDownLatch latch = new CountDownLatch(num);
    do {
        final int current = num;
        executor.execute(new Runnable() {
            @Override
            public void run() {
                resultList.add(doSomeThing(current));
                System.out.println(Thread.currentThread().getName()+":"+current);
                latch.countDown(); //减减操作
            }
        });
        num--;
    }while(num > 0);
    
    try {
        latch.await(1,TimeUnit.MINUTES); //挂起状态,latch的count为0才会往后执行
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("=====多线程任务执行完毕========");
    resultList.forEach(it->{
        System.out.println(it);
    });
    
}
private static int doSomeThing(int num) {
    try {
        Thread.sleep(200); //模拟耗时业务
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return num;
}
}

执行结果:
pool-1-thread-1:100
pool-1-thread-5:96
pool-1-thread-8:93
...
=====多线程任务执行完毕========
100
99
97
....
省略掉一部分输出

相关文章

网友评论

      本文标题:CountDownLatch的应用

      本文链接:https://www.haomeiwen.com/subject/hltrfqtx.html