java多线程——闭锁和栅栏

题目描述 -闭锁

题目

有3个线程,线程A和线程B并行执行,线程C需要和线程A和B执行完成后才能执行,使用闭锁

CountDownLatch实现

解题思路:

创建一个类 :Abc Test

CountDownLatch初始化值为2

新增 A B线程,在线程里执行逻辑后,计算-1

countDownLatch.countDown()
新增C线程,等待A,B线程来完成
countDownLatch.await();
执行相关的逻辑

代码详解:

AbcTest:


package cn.xiaoxuzhu.daily;
 
import java.util.concurrent.CountDownLatch;
 
public class AbcTest {
    public static void main(String[] args) {
        CountDownLatch countDownLatch =new CountDownLatch(2);
        //线程A
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
 
                }catch (InterruptedException e){
                    e.printStackTrace();
 
                }
                System.out.println(Thread.currentThread().getName()+":"+"线程A执行结束");
                countDownLatch.countDown();
            }
        },"线程A").start();
        //线程B
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+":"+"线程B执行结束");
                countDownLatch.countDown();
            }
 
        },"线程B").start();
 
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                  countDownLatch.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+":"+"线程C执行结束");
                countDownLatch.countDown();
            }
 
        },"线程C").start();
 
 
 
 
    }
}


全部评论
君之佳作,吾看甚欢,今谢君不吝共享,让吾窥得其中之奥妙,亦请君为我文指点一二!
点赞 回复 分享
发布于 2022-08-22 09:11 湖南

相关推荐

Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
3 1 评论
分享
牛客网
牛客企业服务