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;
- Is the possible? What are the implications?
- 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?
- 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?
It’s definitely possible and legal. If your
Runnablehas no state (no fields), then everything will be fine. If yourRunnabledoes have mutable state, then you may need to use one of Java’s many mutual exclusion mechanisms likeReentrantLockor thesynchronizedkeyword. Because both Threads will be mutating the fields of the sameRunnableobject.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…