If I create a runnable object
Runnable run = new MyRunnable();
And then pass the same exact object to two thread constructors and run them
new Thread(run).start;
new Thread(run).start;
It's definitely possible and legal. If your Runnable
has no state (no fields), then everything will be fine. If your Runnable
does have mutable state, then you may need to use one of Java's many mutual exclusion mechanisms like ReentrantLock
or the synchronized
keyword. Because both Threads will be mutating the fields of the same Runnable
object.
No, you created and ran two different Threads. They simply call Runnable.run()
.
It's not out of the realm of possibility. I wouldn't even say it's necessarily bad practice. Specific situations where you might do this left as an exercise to the reader...
- Is the possible? What are the implications?
Yes it is possible.
The implication is that any state in the Runnable is (potentially) shared by all threads, and access to / update of that state needs to be properly synchronized.
- If I call Thread.sleep(0); in class MyRunnable, will both threads sleep because they are the same object, or is the thread entity completely separate from the object?
No, they won't.
The Thread is logically distinct from the Runnable
. Calling Thread.sleep()
doesn't directly effect the Runnable
and other threads that may be sharing it. (It could effect other threads indirectly; e.g. if one thread sleeps while it is holding the Runnable's primitive lock, and the other threads need to acquire the lock to make progress.)
- Would there ever be a reason to do this, if not please still answer the two questions above, because I don't think I fully understand the thread mechanism yet?
You might do this if there is no thread-specific state associated with the Runnable
and you wanted to minimize space overheads, or the overheads of initializing the Runnable
objects. But use-cases where those overheads are significant are rare in practice.
In the vast majority of real-world use-cases, each thread needs a distinct Runnable
instance anyway ... because you need to tell each thread to do something different to the others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With