如何让线程在java中睡眠特定的时间?

我有一个场景,我希望一个线程睡眠特定的时间。

码:

public void run(){ try{ //do something Thread.sleep(3000); //do something after waking up }catch(InterruptedException e){ // interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds? } } 

现在,我如何处理我试图运行的线程在完成睡眠之前被中断的exception命中的情况? 线程在被中断后唤醒并且它是否进入可运行状态,或者只有在它进入runnable之后它才会进入catch块?

当您的线程被中断命中时,它将进入InterruptedException catch块。 然后,您可以检查线程花费多长时间睡眠并计算出睡眠时间。 最后,不要吞下exception,最好还原中断状态,以便调用堆栈上方的代码可以处理它。

 public void run(){ //do something //sleep for 3000ms (approx) long timeToSleep = 3000; long start, end, slept; boolean interrupted; while(timeToSleep > 0){ start=System.currentTimeMillis(); try{ Thread.sleep(timeToSleep); break; } catch(InterruptedException e){ //work out how much more time to sleep for end=System.currentTimeMillis(); slept=end-start; timeToSleep-=slept; interrupted=true } } if(interrupted){ //restore interruption before exit Thread.currentThread().interrupt(); } } 

根据此页面,您必须对其进行编码以按您希望的方式运行。 使用睡眠上方的线程将被中断,您的线程将退出。 理想情况下,您将重新抛出exception,以便启动线程时可以采取适当的操作。

如果您不希望这种情况发生,您可以将整个事情放在一个while(true)循环中。 现在,当中断发生时,睡眠中断,你吃exception,然后循环开始新的睡眠。

如果你想完成3秒的睡眠,你可以通过比较10次300毫秒的睡眠来近似它,并将循环计数器保持在while循环之外。 当你看到中断时,吃掉它,设置一个“我必须死”的标志,然后继续循环,直到你睡得足够。 然后以受控方式中断线程。

这是一种方式:

 public class ThreadThing implements Runnable { public void run() { boolean sawException = false; for (int i = 0; i < 10; i++) { try { //do something Thread.sleep(300); //do something after waking up } catch (InterruptedException e) { // We lose some up to 300 ms of sleep each time this // happens... This can be tuned by making more iterations // of lesser duration. Or adding 150 ms back to a 'sleep // pool' etc. There are many ways to approximate 3 seconds. sawException = true; } } if (sawException) Thread.currentThread().interrupt(); } } 
  1. 根据我的经验使用睡眠通常是为了弥补程序中其他地方的不良时间,重新考虑!
  2. 试试这个:

     public void run(){ try{ //do something long before = System.currentTimeMillis(); Thread.sleep(3000); //do something after waking up }catch(InterruptedException e){ long diff = System.currentTimeMillis()-before; //this is approximation! exception handlers take time too.... if(diff < 3000) //do something else, maybe go back to sleep. // interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds? } } 
  3. 如果你自己不打扰睡眠,为什么这个线程会被唤醒? 看来你做错了什么......

我这样使用它:

因此没有必要等待特定时间结束。

 public void run(){ try { //do something try{Thread.sleep(3000);}catch(Exception e){} //do something }catch(Exception e){} } 

你为什么要睡3秒钟? 如果只是在一段时间后执行某些操作,请尝试使用Timer 。