根据 Javadoc: CountDownLatch 使用给定计数进行初始化。 wait 方法会阻塞,直到当前计数达到零。
这意味着在下面的代码中,因为我将 CountDownLatch 初始化为 1。一旦闩锁调用倒计时,所有线程都应该从其等待方法中解除阻塞。
但是,主线程正在等待所有线程完成。而且,我没有将主线程加入到其他线程的末尾。为什么主线程在等待?
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
public class Sample implements Runnable {
private CountDownLatch latch;
public Sample(CountDownLatch latch)
{
this.latch = latch;
}
private static AtomicLong number = new AtomicLong(0);
public long next() {
return number.getAndIncrement();
}
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
for (int threadNo = 0; threadNo < 4000; threadNo++) {
Runnable t = new Sample(latch);
new Thread(t).start();
}
try {
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
latch.await();
Thread.sleep(100);
System.out.println("Count:"+next());
} catch (Exception e) {
e.printStackTrace();
}
}
}
最佳答案
尝试运行以下代码的修改版本:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
public class Test implements Runnable {
private CountDownLatch latch;
public Test(CountDownLatch latch)
{
this.latch = latch;
}
private static AtomicLong number = new AtomicLong(0);
public long next() {
return number.getAndIncrement();
}
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
for (int threadNo = 0; threadNo < 1000; threadNo++) {
Runnable t = new Test(latch);
new Thread(t).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( "done" );
}
@Override
public void run() {
try {
Thread.sleep(1000 + (int) ( Math.random() * 3000 ));
System.out.println(next());
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
您应该看到类似以下内容:
0
done
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
这表明主线程实际上在第一个线程调用 latch.countDown()
之后解除了对 latch.await()
调用的阻塞
关于java - CountDownLatch - 理解await 和countDown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9833636/