public class CountDownLatchDemo {
private static AtomicInteger a = new AtomicInteger();
public static void main(String[] args) {
int count = 50;
for (int i = 0; i < count; i++) {
new Thread(()->{
for (int j = 0; j < 1000; j++) {
a.getAndIncrement();
}
}).start();
}
System.out.println(a.get());
}
}
这段代码我们理想的结果得到50000,但是main线程跑的太快,thread线程执行太耗时,结果小于5000
可以让main线程睡眠来等待thread线程执行完,但是这种做法不精确,此时可以使用CountDownLatch解决
public class CountDownLatchDemo {
private static AtomicInteger a = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
int count = 50;
CountDownLatch countDownLatch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
new Thread(()->{
try {
for (int j = 0; j < 1000; j++) {
a.getAndIncrement();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}).start();
}
// try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); };
countDownLatch.await(); // 通过await()阻塞main线程,直到thread线程全部执行完
System.out.println(a.get());
}
}