zoukankan      html  css  js  c++  java
  • 解决Java的wait(long mills)方法不能区分其返回是由于超时还是被唤醒的问题

    wait(long mills) 没有返回值,所以区分不了其返回是由于超时还是被唤醒,因此需要引入一个布尔变量,来表示它的返回类型。

    class WaitTimeOut {
        private volatile boolean ready = false; // 如果是true,则表示是被唤醒
    
        public synchronized void notify0() {
            ready = true;
            notify();
        }
    
        public synchronized void wait0(long mills) throws InterruptedException {
            long begin = System.currentTimeMillis();
            long rest = mills;
            if (rest == 0L) {
                wait(0);
            } else {
                while (!ready && rest > 0) { // 如果被唤醒(ready为true),或超时(rest <= 0)则结束循环
                    wait(rest);
                    rest = mills - (System.currentTimeMillis() - begin); // 计算剩余时间
                }
                if (ready) {
                    System.out.println("被唤醒");
                } else {
                    System.out.println("超时退出");
                }
            }
        }
    
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(2);
            WaitTimeOut waiter = new WaitTimeOut();
            pool.execute(() -> {
                try {
                    waiter.wait0(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            pool.execute(waiter::notify0);
        }
    }
    

      

  • 相关阅读:
    java操作docker示例(docker-java)
    istio实现对外暴露服务
    istio实现自动sidecar自动注入(k8s1.13.3+istio1.1.1)
    k8s1.13.3安装istio(helm方式)
    wrk http压测工具介绍
    etcd 相关介绍
    openresty 常用API学习
    Lua 相关知识点
    Lua 获取table的长度
    Lua 字符串相关操作
  • 原文地址:https://www.cnblogs.com/yuanyb/p/13380065.html
Copyright © 2011-2022 走看看