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)
¥ 我要打赏 纠错/补充 收藏
哥,这回真没有了