Java教程

Java sleep()方法

线程类的 sleep()方法用于使线程休眠指定的时间。

语法

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

参数

millis: It defines the length of time to sleep in milliseconds
nanos: 0-999999 additional nanoseconds to sleep

返回

It does not return any value.

抛出

IllegalArgumentException: 如果millis的值为负或nanos的值不在0-999999范围内。
InterruptedException: 是否有任何线程中断了当前线程。引发此异常时,将清除当前线程的中断状态。

示例1

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)

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4