CountDownLatch的使用---仗剑走天下

 
讲解:
 
首先要知道此类提供的功能是:
判断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();
    }
}

发布了475 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32370913/article/details/105578162