1. 程式人生 > >java多執行緒-Thread的sleep方法

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方法並不釋放鎖。