• 解决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);
        }
    }
    

      

  • 相关阅读:
    JavaScript创建对象及对象继承
    Shell基础学习小结
    深入理解Java反射
    STL"源码"剖析-重点知识总结
    Java IO工作机制分析
    优先队列原理与实现
    CleanBlog(个人博客+源码)
    线性时间排序
    深入理解FTP协议
    Spring学习之AOP总结帖
  • 原文地址:https://www.cnblogs.com/yuanyb/p/13380065.html
Copyright © 2020-2023  润新知