根据 Javadoc: CountDownLatch 使用给定的计数进行初始化。await 方法阻塞,直到当前计数达到零。
这意味着在下面的代码中,因为我将 CountDownLatch 初始化为 1。一旦锁存器调用倒计时,所有线程都应该从它的 await 方法中解除阻塞。
但是,主线程正在等待所有线程完成。而且,我没有将主线程加入到其他线程的末尾。为什么主线程在等待?
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();
}
}
}