• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving this to the Threads and Synchronization forum...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic