GB11
GB11

Reputation: 290

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

Upvotes: 1

Views: 7816

Answers (3)

Nikolai Manek
Nikolai Manek

Reputation: 1008

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

Upvotes: 0

Parvez
Parvez

Reputation: 641

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

Upvotes: 0

RaviH
RaviH

Reputation: 3584

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.

Upvotes: 3

Related Questions