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(); } }