wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes Is a Thread class a one-run wonder? 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 "Is a Thread class a one-run wonder?" Watch "Is a Thread class a one-run wonder?" New topic
Author

Is a Thread class a one-run wonder?

Dan Kempten
Greenhorn

Joined: Dec 26, 2008
Posts: 25
This is my hopper which hops in 1 second intervals. I can call 5 1 second hops with fiveHops() and it will
function fine the first time.

However the second time I call fiveHops() it has an java.lang.IllegalThreadStateException

for timing reasons I don't want to call hopper = new Hopper() each time I call fiveHops()

How can the hopper object be reset in sufficient manner to stop calling this exception??

is a Thread object meant to always be used once and then discarded??


Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41146
    
  45
From the javadocs of the java.lang.Thread#start() method: It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Why don't you want to create 4 additional objects? Object creation and the resulting memory management will likely have a performance impact that is not even measurable.


Ping & DNS - my free Android networking tools app
Sam Epple
Greenhorn

Joined: Jul 11, 2008
Posts: 4
Thanks for the tip Ulf.
It is measurable. 13 ms of time spent doing new Hopper()
when doing a 50 ms hop is a 26% bite.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Then you have to come up with a different scheme. You can't re-start the same thread. You could make Hopper not-a-Thread, and use a single thread that waits on a signal that it should go (then re-send the Hopper to run as that signal.) This can be done a number of ways, such as through TimerTasks, or ThreadPoolExecutor (or ScheduledThreadPoolExecutor).


Steve
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is a Thread class a one-run wonder?
 
Similar Threads
JAVA RAndom Numbers
closing thread and its childs
will wait and notify work in this scenario?
Synchronizing between two threads, one implements Runnable the other extends Thread
Slowing Down a program