如果此方法的变量'commonSet'是类级别字段,下面的代码是否会导致相同的问题?如果它是一个类级别的字段,那么我将不得不包装添加到在同步块内设置操作,因为HashSet不是线程安全的。我应该在下面的代码中做同样的事情,因为多个线程正在添加到集合中,甚至当前线程可能会继续对集合进行变异。线程安全 - 最终本地方法变量传递给线程?
public void threadCreatorFunction(final String[] args) {
final Set<String> commonSet = new HashSet<String>();
final Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
commonSet.add(newValue());
}
}
};
new Thread(runnable, "T_A").start();
new Thread(runnable, "T_B").start();
}
对'commonSet'的引用是通过使用final来锁定的。但是在它上面运行的多个线程仍然会破坏集合中的值(它可能包含重复项?)。其次,混淆是因为'commonSet'是一个方法级变量 - 它的调用方法(threadCreatorFunction)和堆栈内存的运行方法的堆栈内存是相同的引用 - 这是正确的吗?
有与此相关的不少问题:
- Why do variables passed to runnable need to be final?
- Why are only final variables accessible in anonymous class?
但是,我看不到他们强调这种共享/传递mutables的线程安全的一部分。
另请参阅http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen – nos 2012-08-06 07:45:36