public class TestThread {
ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
TestThread testThread = new TestThread();
final List<String> list = new ArrayList<>();
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.print(list);
}
}
testThread.executorService.submit(runnable);
}
}
在这段代码代码片段中,在主线程中创建了一个列表。并且在可运行的实例中将在由 ExecutorService 管理的其他线程中访问此列表。
所以我的问题是在这种情况下是否会存在线程内存可见性问题?据我所知,如果不使用 sychronization/volatile,一个线程无法看到(或完全看到)另一个线程中的值。
最佳答案
您必须将该变量设置为 final
的原因是您的 Runnable
可以使用它的副本创建(这也是 final
).
final
对象构造期间初始化的字段保证正确发布到所有线程。
因此它将看到列表
。
但是,ArrayList
不是线程安全的,因此您不应该与多个线程共享它(如果您打算修改它)。
关于java - 如果可运行/可调用访问外部类变量,是否存在任何内存可见性问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790178/