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

  

原文地址:https://www.cnblogs.com/yuanyb/p/13380065.html