如果要更改,Runnable是否共享数据结构? [英] Does Runnable share the data structure if they are getting changed?
问题描述
我通过以下方式创建Runnable:
I am creating a Runnable in the following way:
public class AbcRunnable implements Runnable
{
Qwe qwe;
Rst rst;
public void run() {
// some operations on qwe and rst which are changing their value
}
}
public class AbcThreadPool {
private final AbcThreadPoolExecutor executor;
public InventoryAvailabilityThreadPool(final AbcRunnableFactory factory,
final Integer poolSize) {
executor = new AbcThreadPoolExecutor(factory, poolSize);
for (int i = 0; i < poolSize; ++i) {
executor.execute(factory.get());
}
}
private static class AbcThreadPoolExecutor extends ThreadPoolExecutor {
private final AbcRunnableFactory factory;
public AbcThreadPoolExecutor(final AbcRunnableFactory factory,
final int poolSize) {
super(poolSize, poolSize, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
this.factory = factory;
allowCoreThreadTimeOut(false);
}
}
}
public class AbcRunnableFactory {
@Override
public AbcRunnable get() {
return new AbcRunnable();
}
}
Qwe和Rst的初始化由guice模块完成,例如:
Initialization of Qwe and Rst is being done by the guice module, say, as follows:
@Provides
@Singleton
private AbcRunnableFactory provideAbcRunnableFactory() {
return new AbcRunnableFactory(
new Qwe(), new Rst());
}
因此,这里AbcRunnable具有2个变量:qwe和rst.我的问题是,不同的Runnable是否具有自己的变量,或者它们会被共享?请帮助解释这一点.
So, here AbcRunnable has 2 variables: qwe and rst. My question here is, do different Runnables have their own variables or are they getting shared? Please help in explaining this.
当试图了解什么是线程安全的时候,我感到非常困惑.因此,这可能是一个非常幼稚的问题.
I am very confused when trying to understand what is thread safe or not. So, this may be a very naive question.
推荐答案
每个AbcRunnable
的新实例将具有其自己的字段集(list1
和map1
).由于您的循环在每次迭代中都调用factory.get()
,并创建了一个新的AbcRunnable
,因此每个线程池任务将具有可运行字段及其包含字段的唯一实例.
Each new instance of AbcRunnable
will have its own set of fields (list1
and map1
). Since your loop is calling factory.get()
in each iteration, and that creates a new AbcRunnable
, each thread pool task will have a unique instance of the runnable and its contained fields.
现在,您还没有显示如何初始化AbcRunnable
中的字段:
Now, you haven't showed how you initialize the fields inside AbcRunnable
:
- 如果在构造函数中创建新的
List
和Map
实例,则线程之间不会共享任何内容,并且代码是线程安全的. - 如果要从外部传递这些值中的任何一个,则不同的
AbcRunnable
实例可能潜在地共享对同一列表/映射的引用,并且您将需要确保对数据的同步访问(或使用并发集合)实现,它已经是线程安全的了.
- If you create new
List
andMap
instances in the constructor, then nothing is shared between threads and your code is thread-safe. - If you are passing in any of these values from the outside, then your different
AbcRunnable
instances could potentially share references to the same list/map and you will need to ensure synchronized access to the data (or use a concurrent collection implementation, which is already thread-safe).
这篇关于如果要更改,Runnable是否共享数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!