JUC輔助類CountDownLatch
阿新 • • 發佈:2022-04-10
想實現六個同學離開教室後,班長關門
錯誤寫法
public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { for (int i = 1; i <=6; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"號同學離開教室了"); },String.valueOf(i)).start(); } System.out.println("班長鎖門了"); } }
效果如下
正確做法(countDownLatch)
import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(6); for (int i = 1; i <=6; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"號同學離開教室了"); //計數 -1 latch.countDown(); },String.valueOf(i)).start(); } //等待 latch.await(); System.out.println("班長鎖門了"); } }
效果如下