讲解:
首先要知道此类提供的功能是:
判断count计数不为0时,同时线程处于wait状态提供在屏障出等待,具体看下面代码实现,如果为0继续运行。
具体是通过await和countDown方法进行的
Demo:计数不为0,线程阻塞状态效果
package com.zcw.demo1;
import java.util.concurrent.CountDownLatch;
/**
* @ClassName : MyService
* @Description :
* @Author : Zhaocunwei
* @Date: 2020-04-17 13:05
*/
public class MyService {
private CountDownLatch countDownLatch = new CountDownLatch(1);//创建1个技术的对象
public void testMethod(){
System.out.println("A");
try {
//当线程执行如下代码时成等待状态,程序不向下继续运行,
countDownLatch.await();
System.out.println("B");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void downMethod(){
System.out.println("X");
//当程序执行如下代码后,计数由1变为0,以前呈等待状态的线程继续向下运行。
countDownLatch.countDown();
}
}
package com.zcw.demo1;
/**
* @ClassName : MyThread
* @Description :
* @Author : Zhaocunwei
* @Date: 2020-04-17 13:13
*/
public class MyThread extends Thread {
private MyService myService;
public MyThread(MyService myService){
super();
this.myService = myService;
}
@Override
public void run(){
myService.testMethod();
}
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
MyThread myThread = new MyThread(myService);
myThread.start();
Thread.sleep(2000);
myService.downMethod();
}
}