CountDownLatch控制三个线程顺序执行

CountDownLatch的两个核心方法:
countObj.countDown() 表示countObj计数减少。
countObj.await() 表示检查countObj若不为0则阻塞,为0,则允许执行


    public class CountLatchDown {
	    public static void main(String[] args) {    
	        CountDownLatch c0 = new CountDownLatch(0); //①
	        CountDownLatch c1 = new CountDownLatch(1); //②
	        CountDownLatch c2 = new CountDownLatch(1); //③
	
	        Thread t1 = new Thread(new Work(c0, c1));
	        //c0为0,t1可以执行。t1的计数器减1
	        Thread t2 = new Thread(new Work(c1, c2));
	        //t1的计数器为0时,t2才能执行。t2的计数器c2减1
	        Thread t3 = new Thread(new Work(c2, c2));
	        //t2的计数器c2为0时,t3才能执行
	
	        t2.start();
	        t1.start();
	        t3.start();
	
	    }
	    //定义Work线程类,需要传入开始和结束的CountDownLatch参数
	    static class Work implements Runnable {
	        CountDownLatch c1;
	        CountDownLatch c2;
	        Work(CountDownLatch c1, CountDownLatch c2){
	            super();
	            this.c1=c1;
	            this.c2=c2;
	        }
	        public void run() {
	            try {
	                c1.await();//前一线程为0才可以执行
	                System.out.println("开始执行线程:"+ Thread.currentThread().getName());
	                c2.countDown();//本线程计数器减少
	            } catch (InterruptedException e) {              
	            }  
	
	        }
	    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CountDownLatchJava多线程中的一个同步工具,可以让一个或多个线程等待其他线程完成后再执行CountDownLatch可以用来实现线程顺序执行,具体步骤如下: 1. 创建CountDownLatch对象,设置计数器数量,即需要等待的线程数量。 2. 在需要等待的线程中,调用CountDownLatch的await()方法,等待其他线程执行完成。 3. 在其他线程中,执行完需要等待的代码后,调用CountDownLatchcountDown()方法,将计数器数量减1。 4. 当计数器数量减为0时,等待的线程会被唤醒,可以继续执行。 示例代码如下: ``` import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(3); //设置计数器数量为3 //线程1 new Thread(() -> { System.out.println("Thread 1 is running"); latch.countDown(); //计数器减1 }).start(); //线程2 new Thread(() -> { System.out.println("Thread 2 is running"); latch.countDown(); //计数器减1 }).start(); //线程3 new Thread(() -> { System.out.println("Thread 3 is running"); latch.countDown(); //计数器减1 }).start(); try { latch.await(); //等待计数器为0 System.out.println("All threads have finished"); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 以上代码中,创建了一个CountDownLatch对象,并设置计数器数量为3。在三个线程中,执行了一些代码后,调用了CountDownLatchcountDown()方法,计数器数量减1。在主线程中,调用了CountDownLatch的await()方法,等待计数器数量为0。当三个线程都完成后,计数器数量减为0,主线程被唤醒,打印了"All threads have finished"。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值