Roxy Roxy - 27 days ago 4x
Java Question

Creating multiple threads with a single instance of Runnable VS. with separate instances for each thread

What is the difference between creating multiple threads with one instance of Runnable for all of them AND with separate instances for each thread. When should I use the first approach and when the second one? Can you give me an example so I can comprehend the two concepts more clearly? I found few similar topics, but I could not entirely understand the contrast between both of the two approaches.


What's the difference...?

The difference---the entire difference---is that if the Runnable class has one or more fields, then those fields will be shared by the several threads if all of the threads are given the same instance, and they will not be shared if each thread is given its own instance.

If the Runnable class does not declare any fields, then there effectively is no difference at all.

Basically, it's up to you to decide which data in your program should be shared between threads and which data should not be shared.

If all of the Runnable fields are shared, (i.e., if you use the same Runnable instance for every thread), then that will make it harder for you to have any data that are not shared.