四、閉鎖之CountDownLatch
阿新 • • 發佈:2018-12-23
一、簡介
閉鎖是Java的一種同步工具類。我們在程式執行過程中,某個任務需要等待其它一個到多個的任務全部完成才會執行,這個等待的期間就叫做閉鎖。
CountDownLatch是閉鎖的一種實現,它支援一組任務在完成之前,其它一個或者多個執行緒一直等待。
JDK文件:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/CountDownLatch.html
二、程式碼示例
import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo {public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); new Thread(() -> { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ " finished"); }).start(); Thread.sleep(5000); latch.countDown(); System.out.println(Thread.currentThread().getName() + " finished"); } }