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("=================="); } }