• 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("==================");
        }
    }
  • 相关阅读:
    C#等同于正则表达式的写法
    操作XML
    对比工具集合
    IIS 部署的网站无法启动
    jdk_1.8 下载之后的配置
    sql server 2008认识 DENSE_RANK
    c# 二分查找算法
    c# 使用栈实现有效的括号
    sql server 自定义标量函数
    虚拟机cenos 重置密码
  • 原文地址:https://www.cnblogs.com/zheaven/p/13214160.html
Copyright © 2020-2023  润新知