java多线程-Thread的sleep方法

Posted 扶不起的刘阿斗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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方法并不释放锁。


以上是关于java多线程-Thread的sleep方法的主要内容,如果未能解决你的问题,请参考以下文章