java多线程-Thread的sleep方法

public static native void sleep(long millis) throws InterruptedException;
sleep是本地静态方法。
sleep的作用是让线程进入TIME_WAITING状态,参数是多少毫秒。
class Test {
    public static void main(String[] args){
        Thread thread = new Thread(()->{
            try {
                Thread.sleep(2000);
                System.out.println("over");
            } catch (InterruptedException e) {
                System.out.println("interrupt");
            }
        });
        thread.start();
    }
}

/**
 结果:2秒后看到over
 */
sleep可被interrupt打断,抛出InterruptedException。
class Test {
    public static void main(String[] args){
        Thread thread = new Thread(()->{
            try {
                Thread.sleep(2000);
                System.out.println("over");
            } catch (InterruptedException e) {
                System.out.println("interrupt");
            }
        });
        thread.start();
        thread.interrupt();
    }
}

/**
 结果:立刻看到interrupt
 */

注意:sleep方法并不释放锁。

猜你喜欢

转载自www.cnblogs.com/liuboyuan/p/10120789.html