JDK 的 “水操作“ 之 假装精确

在java祖传父类Object里面有这么一个方法

public final native void wait(long timeout) throws InterruptedException;

这个方法的作用是让当前线程等待,退出CPU退出监视器

直到Object.notify()、Object.notifyAll() 刚好选中该线程 、超时、被中断

他有一个兄弟方法,水的一匹,直接贴上代码

public final void wait(long timeout, int nanos) throws InterruptedException {
     
        if (timeout < 0) {
     
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
     
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
     
            timeout++;
        }

        wait(timeout);
    }

当我们不点进源码时看其参数,心想:jdk有点6的嘛,实现了nanos级别的时间控制

一旦你点进来看到源码,就这????

假装精确nanos级别的时间控制,实则只要第二个参数大于0,milliseconds就加1,辣鸡,tui

类似的操作还有

在线程祖传父类Thread里面有这么一个方法

public static native void sleep(long millis) throws InterruptedException;

此方法作用为让当前线程等待,退出CPU,与wait()有一点区别就是,sleep()不会退出监视器

直接看其兄弟方法

public static void sleep(long millis, int nanos) throws InterruptedException {
     
        if (millis < 0) {
     
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
     
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
     
            millis++;
        }

        sleep(millis);
    }

稍微比wait()精确了一丢丢,至少是大于等于500000才加1了,且人家在millis等于0时基本上就加1

Thread里面还有一个方法,不多bb,直接笑

public final synchronized void join(long millis) throws InterruptedException
public final synchronized void join(long millis, int nanos) throws InterruptedException {
     
        if (millis < 0) {
     
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
     
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
     
            millis++;
        }

        join(millis);
    }

你可能感兴趣的:(java,jdk)