java多线程-java CountDownLatch

sancaiodm Java 2021-09-12 1319 0

CountDownLatch是一个同步的辅助类,允许一个或多个线程一直等待,直到其它线程完成它们的操作。CountDownLatch这个类能够使一个线程或多个线程等待其他线程完成各自的工作后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。CountDown是倒数计数,所以CountDownLatch的用法通常是设定一个大于0的值,该值即代表需要等待的总任务数,每完成一个任务后,将总任务数减一,直到最后该值为0,说明所有等待的任务都执行完了,“门闩”此时就被打开,后面的任务可以继续执行。

这里就涉及两个问题:

1.如何让一个或多个线程一直等待;

2.如何让这些线程知道其它线程已经完成它们的操作


          CountDownLatch的一个非常典型的应用场景是:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行,假如我们这个想要继续往下执行的任务调用一个CountDownLatch对象的await()方法,其他的任务执行完自己的任务后调用同一个CountDownLatch对象上的countDown()方法,此时CountDownLatch的计数器值就会减1。这个调用await()方法的任务将一直阻塞等待,直到这个CountDownLatch对象的计数值减到0为止。 


切记:等待闭锁的线程(即调用await()方法)会一直处于堵塞状态,如果你是在主线程中调用此方法,则会堵塞主线程


Worker

import java.util.Random;  
import java.util.concurrent.CountDownLatch;  
import java.util.concurrent.TimeUnit;  
  
public class Worker implements Runnable{  
      
    private CountDownLatch downLatch;  
    private String name;  
      
    public Worker(CountDownLatch downLatch, String name){  
        this.downLatch = downLatch;  
        this.name = name;  
    }  
      
    public void run() {  
        this.doWork();  
        try{  
            TimeUnit.SECONDS.sleep(new Random().nextInt(10));  
            //如果此处休眠换成Thread.sleep()方法  会有异常的结果,看本方最下方记录
        }catch(InterruptedException ie){  
        }  
        System.out.println(this.name + "活干完了!");  
        this.downLatch.countDown();  
          
    }  
      
    private void doWork(){  
        System.out.println(this.name + "正在干活!");  
    }  
      
}

boss老板

import java.util.concurrent.CountDownLatch;  

public class Boss implements Runnable {  
  
    private CountDownLatch downLatch;  
      
    public Boss(CountDownLatch downLatch){  
        this.downLatch = downLatch;  
    }  
      
    public void run() {  
        System.out.println("老板正在等所有的工人干完活......");  
        try {  
            this.downLatch.await();  
        } catch (InterruptedException e) {  
        }  
        System.out.println("工人活都干完了,老板开始检查了!");  
    }  
}

Main主类

public class CountDownLatchDemo {  
  
    public static void main(String[] args) {  
        ExecutorService executor = Executors.newCachedThreadPool();           
        CountDownLatch latch = new CountDownLatch(4);    //此处是传入4 ,计数器的值是4      
        Worker w1 = new Worker(latch,"张三");      //构建三个工作者
        Worker w2 = new Worker(latch,"李四");  
        Worker w3 = new Worker(latch,"王二");          
        Boss boss = new Boss(latch);  
        executor.execute(w3);  
        executor.execute(w2);  
        executor.execute(w1);  
        executor.execute(boss);           
        executor.shutdown();  
    }  
}

如上,这里只构建了3个工作者,但是在初始化latch时计数器传入的值是 4 ,这样的话就会造成latc的计数量永远都不会为0,执行程序看看输出:
王二正在干活!
老板正在等所有的工人干完活......
张三正在干活!
李四正在干活!    //完成
张三活干完了!    //完成
李四活干完了!
王二活干完了!   //完成

如上张三,李四,王五都完成了工作,但老板始终没有去检查工作,
结论:
CountDownLatch允许一个或多个线程一直等待,直到其它线程全部完成它们的操作。线程才会继续执行下去


再来看一个稍微复杂点的例子,10个选手比赛跑步,在枪响后同时起跑,全部到达终点后比赛结束:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CountDownLatchDemo {

    private static int PLAYER_NUM = 10;

    public static void main(String[] args) {

        final CountDownLatch beginSignal = new CountDownLatch(1);
        final CountDownLatch endSignal = new CountDownLatch(PLAYER_NUM);

        ExecutorService executorService = Executors.newFixedThreadPool(PLAYER_NUM);

        for(int i=0;i<PLAYER_NUM;i++){
            final int num = i+1;
            Runnable runner = new Runnable(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    System.out.println("No. "+num+" is waiting...");
                    try {
                        beginSignal.await();
                        System.out.println("No. "+num+" begin running");
                        Thread.sleep((long) (Math.random() * 10000));
                        System.out.println("No." + num + " arrived");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }finally{
                        endSignal.countDown();
                    }
                }

            };
            executorService.execute(runner);
        }

        System.out.println("before Game Start");
        beginSignal.countDown();
        System.out.println("Game Start");
        System.out.println("---In the middle of the game---");
        try {
            endSignal.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            System.out.println("Game Over!");
            executorService.shutdown();
        }

    }

}

输出:
No. 1 is waiting...
No. 3 is waiting...
No. 4 is waiting...
No. 5 is waiting...
No. 2 is waiting...
No. 6 is waiting...
No. 10 is waiting...
before Game Start
No. 9 is waiting...
No. 7 is waiting...
No. 8 is waiting...
No. 10 begin running
No. 6 begin running
No. 5 begin running
No. 2 begin running
No. 7 begin running
No. 4 begin running
No. 3 begin running
No. 1 begin running
No. 9 begin running
Game Start
No. 8 begin running
---In the middle of the game---
No.1 arrived
No.9 arrived
No.2 arrived
No.6 arrived
No.7 arrived
No.8 arrived
No.3 arrived
No.4 arrived
No.5 arrived
No.10 arrived
Game Over!


CountDownLatch封装类:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Counter {

    //private AtomicInteger mCurrentValue;
    private CountDownLatch mCurrentValue ;

    public Counter(int maxValue) {
        mCurrentValue = new CountDownLatch(maxValue);
    }

    public void count() {
        mCurrentValue.countDown();
    }

    public void waitCount() {
        try{
            mCurrentValue.await();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public void waitCount(long timeout) {
        try {
            //await(long timeout, TimeUnit unit)超时等待机制:
            mCurrentValue.await(timeout,TimeUnit.MILLISECONDS);
            if (mCurrentValue.getCount() > 0) {
                android.util.Log.i(this.toString(),"wait timeout");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Thread.sleep()和TimeUnit.SECONDS.sleep()的区别

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class countDownlatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        ExecutorService executor = Executors.newCachedThreadPool();
        for(int i=0;i<5;i++){
        	executor.submit(new countDownlatchTest().new Worker(i,countDownLatch));
        }
        System.out.println("await之后的要等所有线程执行完成");
        countDownLatch.await();
        System.out.println("线程执行结束 最后执行的任务,");
    }
 
    private class Worker  implements Runnable{
        private int id;
        private CountDownLatch latch;
        public Worker(int id,CountDownLatch latch){
            this.id = id;
            this.latch = latch;
        }
        public void run() {
            synchronized (this){
                try {
                	 System.out.println("线程id:"+id);
                	 TimeUnit.SECONDS.sleep(new Random().nextInt(10)); 
                	 latch.countDown();
                     System.out.println("线程组任务结束,"+id+",继续执行各自的任务");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
               
            }
        }
    }
}
输出:
线程id:0
线程id:4
线程id:1
线程id:3
await之后的要等所有线程执行完成
线程id:2
线程组任务结束,1,继续执行各自的任务
线程组任务结束,2,继续执行各自的任务
线程组任务结束,0,继续执行各自的任务
线程组任务结束,3,继续执行各自的任务
线程组任务结束,4,继续执行各自的任务
线程执行结束 最后执行的任务,


如果把TimeUnit.SECONDS.sleep(new Random().nextInt(10)); 换成Thread.sleep(1000);

image.png


如有知道为什么的请帮忙留言解答,谢谢!!!

评论