標籤:
In order to work effectively with multithreaded code, it’s important to have the basic
facts about monitors and locks at your command. This checklist contains the main
facts that you should know:
Synchronization is about protecting object state and memory, not code.
同步是關於保護對象的狀態和記憶體,不是代碼.
Synchronization is a cooperative mechanism between threads. One bug can break the cooperative model and have far-reaching consequences.
同步是線程間相互合作的一種機制,一個bug就可能打破合作模型,導致嚴重的後果.
Acquiring a monitor only prevents other threads from acquiring the monitor—it does not protect the object.
一個線程獲得一個monitor,只能防止其它線程獲得這個monitor---monitor不能保護對象.
Unsynchronized methods can see (and modify) inconsistent state, even while the object’s monitor is locked.
沒有同步的方法能看到(且修改)對象不一致的狀態,即使對象的monitor已被上鎖.
Locking an Object[] doesn’t lock the individual objects.
對一個Object[]數組上鎖,並不能鎖住數組內的每一個對象.
Primitives are not mutable, so they can’t (and don’t need to) be locked.
原生類型是不可變的,所以他們不能(而且沒必要)去上鎖.
synchronized can’t appear on a method declaration in an interface.
同步不能出現在介面的方法上.
Inner classes are just syntactic sugar, so locks on inner classes have no effect on the enclosing class (and vice versa).
內部類僅僅是文法糖而已,所以對內部類上鎖不會影響包含它的類(反之亦然).
Java’s locks are reentrant. This means that if a thread holding a monitor encounters a synchronized block for the same monitor, it can enter the block.
Java
- 的鎖是重入鎖.這就意味著如果一個線程碰到一個同步塊而擁有了一個
monitor,這個線程還是可以進入這個同步塊.
Working with Threads-Java in a Nutshell, 6th