Java多线程使用 CountDownLatch等待其他线程执行完成

Java多线程使用 CountDownLatch等待其他线程执行完成

CountDownLatch允许一个或者多个线程去等待其他线程完成操作。

java.lang.Concurrent包下的可阻塞类CountDownLatch(倒数计数器),基于基类AQS(AbstractQueuedSynchronizer)标准队列同步器类。在同步状态state中保存的是当前的计数值。

CountDownLatch接收一个int型参数,表示要等待的工作线程的个数。

countDown()调用releaseShared(int arg),从而导致计数器值递减,并且计数器值为零时,解除所有等待线程的阻塞。

await()调用acquireSharedInterruptibly(int arg),当计数器值为零时,acquire将立即返回,否则将阻塞。

await():阻塞当前线程,将当前线程加入AQS的阻塞队列;
countDown():对计数器进行递减操作,当计数器递减至0时,当前线程会取唤醒阻塞队列中的所有线程。

简单示例:
主线程等待其他线程执行完成之后执行业务:

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

import static java.lang.Thread.sleep;

public class countdownLatchTest {
    
    
    public static void main(String[] args) {
    
    
        // 新建CountDownLatch
        CountDownLatch latch = new CountDownLatch(3);
        // 新建线程池
        ExecutorService service = Executors.newFixedThreadPool(4);
        // 提交任务
        service.submit(()->{
    
    
            System.out.println("1-begin....");
            try {
    
    
                sleep(1);
                // CountDownLatch - 1
                latch.countDown();
            } catch (InterruptedException e) {
    
    
                throw new RuntimeException(e);
            }
            System.out.println("1-end....");
        });

        service.submit(()->{
    
    
            System.out.println("2-begin....");
            try {
    
    
                sleep((long) 1.5);
                latch.countDown();
            } catch (InterruptedException e) {
    
    
                throw new RuntimeException(e);
            }
            System.out.println("2-end....");
        });

        service.submit(()->{
    
    
            System.out.println("3-begin....");
            try {
    
    
                sleep(2);
                latch.countDown();
            } catch (InterruptedException e) {
    
    
                throw new RuntimeException(e);
            }
            System.out.println("3-end....");
        });

        service.submit(()->{
    
    
            System.out.println("waiting...");
            try {
    
    
                latch.await();
            } catch (InterruptedException e) {
    
    
                throw new RuntimeException(e);
            }
            System.out.println("等待结束");
        });
        service.shutdown();
    }
 }

在这里插入图片描述
写的比较粗糙,只是简单记录一下如何使用。

猜你喜欢

转载自blog.csdn.net/qq_36944952/article/details/126196175