latch.await();生效的三种方法


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM