【发布时间】:2019-05-04 03:04:43
【问题描述】:
我正在通过以下方式创建一个 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。我的问题是,不同的 Runnables 有自己的变量还是共享?请帮忙解释一下。
当我试图理解什么是线程安全时,我很困惑。所以,这可能是一个非常幼稚的问题。
【问题讨论】:
-
你为什么要费心包装线程池执行器?制造工厂玻璃?你想解决什么问题?你没有发现
Executors类吗?
标签: java multithreading runnable