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

aru*_*unc 12 java multithreading sleep

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

码:

    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?
                }
        }
Run Code Online (Sandbox Code Playgroud)

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

dog*_*ane 10

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


cod*_*ber 1

  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?
            }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 如果你自己不中断睡眠,为什么这个线程会被唤醒?看来你正在做一些非常错误的事情......