java thread sleep_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)

¥ 我要打赏 纠错/补充 收藏

哥,这回真没有了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值