1.中斷主線程使await()生效
package com.dwz.utils; import java.util.concurrent.CountDownLatch; /** * 中斷主線程使await()生效 */ public class CountDownLatchExample4 { public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final Thread mainThread = Thread.currentThread(); new Thread() { public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } mainThread.interrupt(); }; }.start(); latch.await(); System.out.println("=================="); } }
2.latch減為0使得await()生效
package com.dwz.utils; import java.util.concurrent.CountDownLatch; /** * latch減為0使得await()生效 */ public class CountDownLatchExample3 { public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); }; }.start(); latch.await(); System.out.println("=================="); } }
3.CountDownLatch.await(long timeout, TimeUnit unit)設置時間自動結束
package com.dwz.utils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * CountDownLatch.await(long timeout, TimeUnit unit)設置時間自動結束 */ public class CountDownLatchExample5 { public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); }; }.start(); latch.await(1000, TimeUnit.MILLISECONDS); System.out.println("=================="); } }