• Post Reply Bookmark Topic Watch Topic
  • New Topic

sleeping thread

 
Neeraj Vij
Ranch Hand
Posts: 315
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

is there any way to invoke a sleeping thread ?

Thanks,
Neeraj
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean "invoke"?

You can prematurely-end the sleep(), by calling interrupt() on the sleeping Thread. Of course, this has to be done from another thread.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure what you mean by invoke. Do you mean invoke methods on the object representing the thread in which case just do it (obviously your in another thread of execution or you'ed be asleep ;-)). You can't restart the thread as such if thats what you mean, you could interrupt the thread to continue its current execution (obviously you need to handle the interruption).
 
Neeraj Vij
Ranch Hand
Posts: 315
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant to say-- can I restart the execution of sleeping thread before it's time specified to sleep has finished.


Thanks,
Neeraj.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say "restart", you mean continue from the statement after the sleep(), yes? If so, this is what you can do with interrupt(). You'd need a try..catch around the sleep(), to catch and squash the InterruptedException (squashing the exception is OK here because the exception is "expected" - you should never squash "unexpected" exceptions).
 
Henry Wong
author
Sheriff
Posts: 22530
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
When you say "restart", you mean continue from the statement after the sleep(), yes? If so, this is what you can do with interrupt(). You'd need a try..catch around the sleep(), to catch and squash the InterruptedException (squashing the exception is OK here because the exception is "expected" - you should never squash "unexpected" exceptions).


Be real careful with this... If the sleeping thread wakes up first, and goes does something else, the extraneous interrupt may do something unexpected. On certain platforms, interrupt will actually interrupt I/O.

The correct solution here is to use wait(timeout) instead. And to use notify() to wake up the thread prematurely. If the "sleeping" thread wakes up first, the notification is simply discarded.

Henry
[ March 06, 2007: Message edited by: Henry Wong ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!