Yes, you can do this when your Runnable
is implemented accordingly.
But you have to be careful your Runnable
implementation does not contain a mutable state. You can control this in your own implementations, but the Runnable
contract does not specify.
// can be used for multiple Threads
class StatelessRunnable {
public void run() {
doSomething();
}
}
// may go bang on the second execution -> use two instances
class StatefulRunnable {
volatile boolean canRun = true;
public void run() {
if(!canRun) throw new IllegalStateException();
canRun = false;
}
}
In the above sample you see that you can use StatelessRunnable
for as many threads as you like. In fact you could even make it a singleton. StatefulRunnable
in contrast can be run only once per instance.
Shared State
Reading Jon's answer I realised there may be scenarios where you actually want to share a state of two Runnable
instances. Of course a stateful Runnable
instance is not always bound to fail with multiple threads, but this is much more trickier to get right than a stateless one.
// willingly share state over threads
class WillinglyStatefulRunnable {
final BlockingQueue<Object> sharedObjects = new BlockingQueue<Object>();
public void run() {
sharedObjects.offer(new Object());
}
}
The above example shows how you could work on a single collection sharedObjects
with multiple threads.
Literature Sidenote:
Item 15 in Joshau Bloch's Effective Java says Minimize Mutabilty. This chapter - in case you have access to the book - addresses similar points in a much more general context. Shortly summarised he states that immutable objects make it easier to reuse instances and reduce the potential of illegal states.