简体   繁体   中英

Waking up a thread in Java with sleep method

I am new to multithreading in Java so excuse me for this question Is there any way to wake up a sleeping thread who was slept by calling the sleep(timeout) method and before that timeout expires ? for example waking him up for some event

Thank you

I have tried this code handling my event to manually sleep/wakeup the thread but it does not work : the thread sleeps but can not resume

              try {
             if(sleepMyThread){

            myThread.sleep(100000);
            sleepMyThread = false;
              }
             else{
            myThread.interrupt();
            sleepMyThread = true;
              }
          }
    catch (InterruptedException e) {
           e.printStackTrace();
    }

Read the documentation of sleep method carefully. It clearly states - method throws InterruptedException . So, you can wake up a sleeping thread by interrupting that thread. However, that is not the way to send events to thread. For sending events (well ... not really event based mechanism is available in core java) you should use a wait - notify mechanism.

Call the interrupt() method on your thread. It will throw an InterruptedException so make sure you handle that.

You can interrupt, catch the interrupt exception and loop through it again. A good simple tutorial is here: http://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM