Another way to create synchronized code is with synchronized statements.
Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.
public void addName(String name) {
// this refer to the instance
// the addName method needs to synchronize changes to lastName and nameCount
synchronized(this) {
lastName = name;
nameCount++;
}
// but also needs to avoid synchronizing other objects' methods
nameList.add(name);
}
The synchronized statement: