gpt4 book ai didi

java - 如果 Runnable 发生变化,它们是否共享数据结构?

转载 作者:行者123 更新时间:2023-12-02 01:31:36 25 4
gpt4 key购买 nike

我通过以下方式创建一个 Runnable:

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 模块完成,如下所示:

@Provides
@Singleton
private AbcRunnableFactory provideAbcRunnableFactory() {
return new AbcRunnableFactory(
new Qwe(), new Rst());
}

所以,这里 AbcRunnable 有 2 个变量:qwe 和 rst。我的问题是,不同的 Runnable 是否有自己的变量,或者它们是否被共享?请帮忙解释一下。

当我试图理解什么是线程安全或什么不是线程安全时,我非常困惑。所以,这可能是一个非常幼稚的问题。

最佳答案

AbcRunnable 的每个新实例都将拥有自己的一组字段(list1map1)。由于您的循环在每次迭代中调用factory.get(),并创建一个新的AbcRunnable,因此每个线程池任务将有一个唯一的可运行实例及其包含的实例字段。

现在,您还没有展示如何初始化 AbcRunnable 中的字段:

  • 如果您在构造函数中创建新的 ListMap 实例,则线程之间不会共享任何内容,并且您的代码是线程安全的。
  • 如果您从外部传入任何这些值,则不同的 AbcRunnable 实例可能会共享对同一列表/ map 的引用,并且您需要确保同步访问数据 (或者使用并发集合实现,它已经是线程安全的)。

关于java - 如果 Runnable 发生变化,它们是否共享数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55979106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com