最佳答案
每次在非 final 类字段上进行同步时都会显示一个警告:
public class X
{
private Object o;
public void setO(Object o)
{
this.o = o;
}
public void x()
{
synchronized (o) // synchronization on a non-final field
{
}
}
}
所以我用下面的方法修改了代码:
public class X
{
private final Object o;
public X()
{
o = new Object();
}
public void x()
{
synchronized (o)
{
}
}
}
我不确定上面的代码是否是在非 final 类字段上进行同步的正确方法。如何同步非 final 字段?