Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do you get a thread to run for one second?

 
Wanki Ho
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say for example I want to take a thread out of a queue and run it for exactly one second and than stick it back into the queue. How would I do that?
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When dealing with threads you should remove phrases like exactly one second from your vernacular. Having said that you can do something like this to come close to what you want:

A couple of things need to be pointed out here. First when the Timer is created a new thread is spawned so this code effectively requires two threads for each worker thread. Second, this assumes you are using a thread pool for implementation since if you just do something like new Thread(new TimedRunner()).start() the thread will die when the timer fires. You could get around this using events or the observer pattern and wrapping the work loop in another loop that waits on this and the external event could signal the thread to wake up with notify or notifyAll.
[ March 14, 2004: Message edited by: Michael Morris ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Threads and Synchronization forum...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic