Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing single runnable object to multiple thread constructors [duplicate]

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;
  1. Is the possible? What are the implications?
  2. 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?
  3. 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?
like image 764
rubixibuc Avatar asked Mar 24 '12 04:03

rubixibuc


2 Answers

  1. 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.

  2. No, you created and ran two different Threads. They simply call Runnable.run().

  3. 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...

like image 126
ulmangt Avatar answered Sep 20 '22 19:09

ulmangt


  1. 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.

  1. 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.)

  1. 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.

like image 43
Stephen C Avatar answered Sep 22 '22 19:09

Stephen C