How to make a thread sleep for specific amount of time in java?

前端 未结 5 514
借酒劲吻你
借酒劲吻你 2021-02-07 16:15

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

Code:

    public void run(){
        try{
            //do something
               


        
5条回答
  •  一生所求
    2021-02-07 17:20

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

提交回复
热议问题