There are several things wrong with this code:
You cannot synchronize
on a primitive.
You could change it to an Integer
but see below.
Synchronizing on a non-final object is not a good idea.
You could make it final
Changing a field while it is being synchronized
on is going to break in some very obscure ways. And now it is final
it will not be allowed.
Probably better to synchronize on another field.
You should also provide a get method for completeness.
With all of these issue fixed your code looks something like this:
public class Example {
private final Object statusLock = new Object();
private Integer status;
public Example(Integer status) {
this.status = status;
}
public void setStatus(Integer newStatus) {
synchronized (statusLock) {
status = newStatus;
}
}
public Integer getStatus() {
return status;
}
}
Now - with this code - the answer to your question is kind of. What happens here is that you lock all access to the status
field through the set method from any other thread while you change it's value.
Notice that I do not synchronise in the get method. If I did then the above statement would change.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…