码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程-Thread的sleep方法

时间:2018-12-14 19:25:26      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:strong   time   方法   tin   ext   print   rgs   参数   color   

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方法

标签:strong   time   方法   tin   ext   print   rgs   参数   color   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!