首页 > 编程语言 > 详细

java多线程-Thread的sleep方法

时间:2018-12-14 18:47:23      阅读:110      评论:0      收藏:0      [点我收藏+]
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方法

原文:https://www.cnblogs.com/liuboyuan/p/10120789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!