Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

等待异步线程池跑完再执行后续代码的方法

等待异步线程池跑完再执行指定方法的三种方式(condition、CountDownLatch、CyclicBarrier),最近本人使用的CountDownLatch

CountDownLatch应用场景

  1. 某个线程需要在其他n个线程执行完毕后再向下执行
  2. 多个线程并行执行同一个任务,提高响应速度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class CountDownLaunchTest {

public static void main(String[] args) throws InterruptedException {
List list = new ArrayList();
for(int i = 1; i<=100; i++){
list.add(i);
}
Long start = System.currentTimeMillis();
for(int i = 0; i<list.size(); i++){
Thread.sleep(100);
}
System.out.println("=====同步执行:耗时"+(System.currentTimeMillis()-start)+"毫秒======");
Long start1 = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(10);
for(int i = 0; i<latch.getCount(); i++){
new Thread(new Test(latch, i, list)).start();
}
latch.await();
System.out.println("=====异步执行:耗时"+(System.currentTimeMillis()-start1)+"毫秒======");
}

static class Test implements Runnable{
private CountDownLatch latch;
private int i;
private List list;
Test(CountDownLatch latch, int i, List list){
this.latch = latch;
this.i = i;
this.list = list;
}

@SneakyThrows
@Override
public void run() {
for(int a = i*10; a<(i+1)*10; a++){
// 执行任务逻辑
Thread.sleep(100);
}
latch.countDown();
}
}
}

评论