java中如何让线程休眠特定时间?

发布于 2024-09-25 07:06:11 字数 510 浏览 2 评论 0原文

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

代码:

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

现在,我如何处理我尝试运行的线程在睡眠完成之前遇到中断异常的情况?另外,线程在被中断后是否会唤醒并进入可运行状态,或者什么时候只有在进入可运行状态后流程才会进入 catch 块?

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

Code:

    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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

孤独难免 2024-10-02 07:06:12

我是这样使用的:

所以不需要等待特定时间结束。

public void run(){

    try {

        //do something

        try{Thread.sleep(3000);}catch(Exception e){}

        //do something

    }catch(Exception e){}

}

I use it this way:

So it is not necessary to wait the specific time to end.

public void run(){

    try {

        //do something

        try{Thread.sleep(3000);}catch(Exception e){}

        //do something

    }catch(Exception e){}

}
独享拥抱 2024-10-02 07:06:12

为什么你想睡正好3秒?如果只是需要在一段时间后执行某些操作,请尝试使用 计时器

Why do you want to sleep for exactly 3 seconds? If it's just having to execute something after some time, try using a Timer.

九厘米的零° 2024-10-02 07:06:11

当您的线程遇到中断时,它将进入 InterruptedException catch 块。然后,您可以检查线程休眠了多少时间,并计算出还有多少时间可以休眠。最后,最好不要吞掉异常,而是恢复中断状态,以便调用堆栈上方的代码可以处理它。

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

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();
    }
}
两仪 2024-10-02 07:06:11

根据此页面,您必须对其进行编码才能表现出来你想要的方式。使用上面的线程你的睡眠将被中断并且你的线程将退出。理想情况下,您应该重新抛出异常,以便启动线程的任何内容都可以采取适当的操作。

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

如果您想完成 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();
    }
}

According to this page you'll have to code it to behave the way you want. Using the thread above your sleep will be interrupted and your thread will exit. Ideally, you'd re-throw the exception so that whatever started the thread could take appropriate action.

If you don't want this to happen, you could put the whole thing in a while(true) loop. Now when the interrupt happens the sleep is interrupted, you eat the exception, and loop up to start a new sleep.

If you want to complete the 3 seconds of sleep, you can approximate it by having, say, 10 sleeps of 300 milliseconds, and keeping the loop counter outside a while loop. When you see the interrupt, eat it, set a "I must die" flag, and continue looping until you have slept enough. Then you interrupt the thread in a controlled manner.

Here's one way:

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();
    }
}
夜吻♂芭芘 2024-10-02 07:06:11
  1. 根据我的经验,使用睡眠通常是为了弥补程序中其他地方的错误时机,请重新考虑!
  2. 试试这个:

    public void run(){
            尝试{
                //做某事
                很久之前 = System.currentTimeMillis();
                线程.sleep(3000);
                //醒来后做一些事情
            }catch(InterruptedException e){
                long diff = System.currentTimeMillis()-之前;
                //这是近似值!异常处理程序也需要时间......
                如果(差异<3000)
                    //做点别的事,也许回去睡觉。
                    // 在睡眠时间完成之前发生中断异常。那么如何让我的线程正好睡眠 3 秒呢?
            }
    }
    
  3. 如果你自己不中断睡眠,为什么这个线程会被唤醒?看来你做了一些非常错误的事情...

  1. using Sleep in my experience is usually to compensate for bad timing somewhere else in the program, reconsider!
  2. try this:

    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. if you do not interrupt the sleep yourself, why would this thread be awoken ? is seems that you are doing something very wrong...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文