JAVA 多线程编程之CountDownLatch使用详解

  

JAVA 多线程编程之CountDownLatch使用详解

什么是CountDownLatch

CountDownLatch是Java中一个同步工具类,可以用于控制线程的等待,它可以让某一个线程等待直到倒计时结束,再开始执行。

CountDownLatch的构造方法

public CountDownLatch(int count) { }

count表示倒计时数量

CountDownLatch的主要方法

public void countDown() //计数器减1
public void await() throws InterruptedException //等待所有计数器归零
public boolean await(long timeout, TimeUnit unit) throws InterruptedException //等待一定时间,如果到了指定的时间,计数器还没有归零,则返回false,否则返回true

CountDownLatch的示例

示例一:等待其他线程执行完毕再开始执行

import java.util.concurrent.CountDownLatch;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);

        Thread thread1 = new Thread(() -> {
            System.out.println("Thread1 is running!");
            countDownLatch.countDown();
        });
        Thread thread2 = new Thread(() -> {
            System.out.println("Thread2 is running!");
            countDownLatch.countDown();
        });

        thread1.start();
        thread2.start();

        countDownLatch.await();

        System.out.println("All threads have finished running!");
    }
}

上述示例中,创建了一个CountDownLatch对象,计数器数值为2,即需要等待两个线程执行完毕后才能继续执行主线程。在两个子线程执行完任务后,分别调用countDown()方法以减少计数器的值,主线程再调用await()方法等待计数器的值为0时继续执行。

示例二:等待其他线程执行完毕并执行其他任务

import java.util.concurrent.CountDownLatch;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);

        Thread thread1 = new Thread(() -> {
            System.out.println("Thread1 is running!");
            countDownLatch.countDown();
        });
        Thread thread2 = new Thread(() -> {
            System.out.println("Thread2 is running!");
            countDownLatch.countDown();
        });

        thread1.start();
        thread2.start();

        countDownLatch.await();

        System.out.println("All threads have finished running!");

        // 等待其他任务执行完毕
        System.out.println("Doing some other work...");
    }
}

上述示例中,与示例一类似,等待两个线程执行完毕后继续执行主线程。但在主线程执行完“All threads have finished running!”后,还可以继续执行其他任务,例如输出“Doing some other work...”

总结

CountDownLatch可以用于线程间的协作,控制线程的执行顺序,让一个或一组线程等待另外一组线程执行完后才执行。通过控制计数器的值,可以实现多个线程的同步执行。

相关文章