This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes How do you get a thread to run for one second? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How do you get a thread to run for one second?" Watch "How do you get a thread to run for one second?" New topic

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

Wanki Ho

Joined: Feb 18, 2004
Posts: 5
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

Joined: Jan 30, 2002
Posts: 3451
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 ]

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Moving this to the Threads and Synchronization forum...

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: How do you get a thread to run for one second?
Similar Threads
kicking off independent task threads in parallel
Different Thread Types
Message is created but not received by the receiver
FBNX: Gui and Threads, asynchronous Swing action execution and GUI updating.
regarding start()