I am trying to have a bunch of runnable threads that can be started one at a time. Something like
First(new Thread() {
public void run() {
//do something
}
});
Is what I'm trying to do impossible?
I am trying to have a bunch of runnable threads that can be started one at a time. Something like
First(new Thread() {
public void run() {
//do something
}
});
Is what I'm trying to do impossible?
The easiest thing to do is to define several
Thread
subclass instances and call the appropriate one depending on what you are trying to do.However, if you really need a single
Thread
object that behaves differently in different circumstances, you can define aThread
subclass that has a state variable for controlling what it does.You could then create your thread and before calling
start()
, callsetAction
, passing one of theAction
values.As an alternative to a state variable, the
run()
method could examine external variables to determine the choice of action. Whether this makes sense (and whether it would be better) depends on your application.Yes, just have multiple private methods:
OR as pointed out by Ted Hopp
This sounds like a bad design to me. If your class is doing different things at different times then it should be split into different classes.
If you are talking about re-using the same background thread to do different things, then I would use a single threaded pool as in @Peter's answer:
The
First
,Second
, andThird
classes would implementRunnable
. They can take constructor arguments if they need to share some state.You can use a single threaded Executor
If you want to start a few threads at the same time
CountDownLatch
is what you need. See an example here: http://www.javamex.com/tutorials/threads/CountDownLatch.shtml.Are you trying to execute multiple runnables sequentially in a single Thread? One after the other?
You could then call
(new Thread(new MultiRunnable(... , ...))).start();
This will execute the first Runnable first, and when that is finnished it will execute the second.
Or generalised to more Runnables: