CountDownLatch 的 getCount()方法不能作为循环条件
package com.deejing.countDownLatch;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(60);
//FutureTask<String> task = new FutureTask<>(new MyThread(latch));
MyThread thread = new MyThread(latch);
System.out.println(latch.getCount());//第一次输出count值
for (int i = 0; i < latch.getCount(); i++) {
new Thread(thread).start();
}
System.out.println(latch.getCount());//创建完线程输出count值
new Thread(new MyThread2(latch)).start();
latch.await();
System.out.println("所有线程都准备好了");
}
}
class MyThread implements Runnable {
private CountDownLatch latch;
public MyThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "已经准备好了");
latch.countDown();//计数器-1
}
}
class MyThread2 implements Runnable {
private CountDownLatch countDownLatch;
public MyThread2(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("唤醒另外一个线程");
}
}
前后两次输出的count值已经减少了
在主线程里的for循环条件是CountDownLatch中的
getCount()
方法返回的值,每次进入循环都会执行一次getCount
,因为在下面新创建的线程中会执行countDown()
方法,会导致count
的值被修改,就会导致循次数比计数器的要小,count永远不会达到0,导致主线程和另外一个线程永远处于阻塞状态。