如何在Java中使线程休眠特定时间? [英] How to make a thread sleep for specific amount of time in java?

查看:674
本文介绍了如何在Java中使线程休眠特定时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我希望线程在特定时间段内休眠.

I have a scenario where i want a thread to sleep for specific amount of time.

代码:

    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?
                }
        }

现在我该如何处理我尝试运行的线程在完成睡眠之前被打断的异常命中的情况?另外,线程在被中断后是否会唤醒并进入可运行状态,或者何时只有在进入可运行状态后流程才开始捕获块?

Now how do i handle the case where the thread i am trying to run is hit with an interrupted exception before the complete of the sleep? Also does the thread wake up after being interrupted and does it go to runnable state or when is it that only after it goes to runnable does the flow go to catch block?

推荐答案

当您的线程被中断打中时,它将进入InterruptedException catch块.然后,您可以检查线程已花费了多少时间进行睡眠,并计算出还有多少时间可以进入睡眠状态.最后,最好不要恢复异常,而是恢复中断状态,以便调用堆栈中更高级别的代码可以处理该异常.

When your thread is hit by an interrupt it will go into the InterruptedException catch block. You can then check how much time the thread has spent sleeping and work out how much more time there is to sleep. Finally, instead of swallowing the exception, it is good practice to restore the interruption status so that code higher up the call stack can deal with it.

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();
    }
}

这篇关于如何在Java中使线程休眠特定时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆