Working with Threads-Java in a Nutshell, 6th

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)