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 mainapp
facts that you should know:oop
Synchronization is about protecting object state and memory, not code.ui
同步是關於保護對象的狀態和內存,不是代碼.spa
Synchronization is a cooperative mechanism between threads. One bug can break the cooperative model and have far-reaching consequences.線程
同步是線程間相互合做的一種機制,一個bug就可能打破合做模型,致使嚴重的後果.code
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
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.
- 的鎖是重入鎖.這就意味着若是一個線程碰到一個同步塊而擁有了一個
monitor,這個線程仍是能夠進入這個同步塊.