当我试图掌握线程安全时,我想知道这个类是否是线程安全的?如果两个线程随时尝试访问其变量,在我看来它是线程安全的,因为:
- final 变量是线程安全的,因为它是不可变的。
- getter 和 setter 是同步的,所以 mObject 一次只能被一个线程获取或设置。因此,两个线程不可能读取不同的值。
- 方法changeObj() 是不同步的,但是其中处理类变量(即mObject)的任何块都是同步的。
如果我错了或者这个类不是线程安全的,请告诉我。
public class MyClass{
private final String = "mystring"; //thread safe because final
private AnObject mObject;
public MyClass(){
//initialize
}
//only one class can set the object at a time.
public synchronized void setObj(AnObject a){
mObject = a;
}
//two threads trying to get the same object will not read different values.
public synchronized AnObject getObj(){
return mObject;
}
//better to synchronize the smallest possible block than the whole method, for performance.
public void changeObj(){
//just using local variables (on stack) so no need to worry about thread safety
int i = 1;
//i and j are just to simulate some local variable manipulations.
int j =3;
j+=i;
synchronized(this){
//change values is NOT synchronized. Does this matter? I don't think so.
mObject.changeValues();
}
}
}