4

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.

2
  • 2
    the first approach is not really good one... Commented Sep 26, 2016 at 10:47
  • 1
    @dit unless you have are writing a thread pool, however you should be using the builtin one, not writing your own, so I agree. ;) Commented Sep 26, 2016 at 10:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can only use the same Runnable across multiple thread if each thread is exactly the same. This is rarely useful. You could have threads in a thread pool work this way, but in this case I would use the built in thread pools, not write your own.

If you need different threads to have a different state, you will need a different Runnable for each Thread as the Runnable holds the state. This is useful when you have threads which need to work on different data even though the code might be the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.