简体   繁体   English

使用Runnable VS的单个实例创建多个线程。 每个线程都有单独的实例

[英]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. 为所有这些线程创建多个线程与Runnable的一个实例并为每个线程创建单独的实例有什么区别。 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. 我发现很少有类似的话题,但我无法完全理解这两种方法之间的对比。

You can only use the same Runnable across multiple thread if each thread is exactly the same. 如果每个线程完全相同,则只能在多个线程中使用相同的Runnable。 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. 如果您需要不同的线程以具有不同的状态,则每个线程都需要不同的Runnable,因为Runnable保持状态。 This is useful when you have threads which need to work on different data even though the code might be the same. 当您拥有需要处理不同数据的线程时,即使代码可能相同,这也很有用。

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. 差异--- 整个差异---是如果Runnable类有一个或多个字段 ,那么如果所有线程都被赋予相同的实例,那么这些字段将被多个线程共享,并且它们将不被共享如果每个线程都有自己的实例。

If the Runnable class does not declare any fields, then there effectively is no difference at all. 如果Runnable类没有声明任何字段,那么实际上没有任何区别。

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, (ie, 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. 如果所有Runnable字段都是共享的(即,如果您为每个线程使用相同的Runnable实例),那么这将使您更难获得任何共享的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM