函数内部的多线程变量访问 [英] Multiple Thread Variable Access inside a function
问题描述
我有一个函数可以启动几个线程(这是一个测试函数),并且其中一个线程会改变变量的状态.由于不能将局部变量标记为volatile,因此我认为该方法中的多个线程将始终具有该变量的更新状态.这样对吗?这是示例代码
I have a function that launches a couple of threads (it's a test function) and one of the threads mutates the state of a variable. Since local variables cannot be marked volatile, I would assume that multiple threads in that method will always have the updated state of the variable. Is this correct? Here is the sample code
public void someMethod() {
MutableBoolean mb = new MutableBoolean(false);
Thread t1 = new Thread() {
public void run() {
while (someCondition) {
if ( mb.getValue() ) {
...do something
}
}
}
}
t1.start();
Thread t2 = new Thread() {
public void run() {
if ( someCondition ) {
mb.setValue(true);
}
}
}
t2.start();
...wait for the threads to complete
}
推荐答案
除非MutableBoolean在其set/get值方法中使用了锁定,否则它是原子操作,那么这不是线程安全的.
Unless MutableBoolean uses a lock in it's set/get value methods, or it's an atomic operation then this isn't threadsafe.
getValue可能正在setValue更新它的同时读取该值.您可以使用布尔值来解决这个问题,但是对于任何更复杂的类型,它可能都会失败.
getValue could be reading the value while setValue is updating it. You might get away with this with a boolean, but for any more complex type it'll probably fail.
在对共享状态的访问周围设置锁,以使其成为线程安全.
Put a lock around the access to shared state to make it thread safe.
这篇关于函数内部的多线程变量访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!