Java Thread sleep()方法

Thread類的sleep()方法用於在指定的時間內睡眠(暫停)線程。

語法

public static void sleep(long milis)throws InterruptedException
public static void sleep(long milis, int nanos)throws InterruptedException

參數

  • millis:它以毫秒為單位定義睡眠時間。
  • nanos:0-999999睡眠的額外納秒數。

異常

  • IllegalArgumentException:如果millis的值為負或nanos的值不在0-999999範圍內。
  • InterruptedException:如果任何線程中斷了當前線程。拋出此異常時,將清除當前線程的中斷狀態。

示例

public class SleepExp1 extends Thread
{
    public void run()
    {
        for(int i=1;i<5;i++)
        {
            try
            {
                Thread.sleep(500);
            }catch(InterruptedException e){System.out.println(e);}
            System.out.println(i);
        }
    }
    public static void main(String args[])
    {
        SleepExp1 t1=new SleepExp1();
        SleepExp1 t2=new SleepExp1();
        t1.start();
        t2.start();
    }
}

執行上面示例代碼,得到以下結果:

1
1
2
2
3
3
4
4
5
5

如您所知,一次只執行一個線程。 如果在指定時間內休眠一個線程,則線程調度程式會選擇另一個線程,依此類推。

例2: 睡眠時間為負時

public class SleepExp2 extends Thread
{
    public void run()
    {
        for(int i=1;i<5;i++)
        {
            try
            {
                Thread.sleep(-500); // sleep time is negative
            }catch(InterruptedException e){System.out.println(e);}
            System.out.println(i);
        }
    }
    public static void main(String args[])
    {
        SleepExp2 t1=new SleepExp2();
        SleepExp2 t2=new SleepExp2();
        t1.start();
        t2.start();
    }
}

執行上面示例代碼,得到以下結果:

Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.IllegalArgumentException: timeout value is negative
    at java.lang.Thread.sleep(Native Method)
    at SleepExp2.run(SleepExp2.java:9)
java.lang.IllegalArgumentException: timeout value is negative
    at java.lang.Thread.sleep(Native Method)
    at SleepExp2.run(SleepExp2.java:9)

上一篇: Java Runtime類 下一篇:無