When it locks a method or a code block, at most one thread can execute this code at the same time. When two concurrent threads access this locked synchronization code block in the same object object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing this code block before it can execute this code block.
The question is, if two threads access different instances of this object, will they still be blocked?
synchronized的用法有以下三种
指定对象加锁。类似于synchronized (instance) {}。
直接作用于实例方法。相当于对当前实例加锁,进入同步方法前要获得当前实例的锁。
直接作用于静态方法。相当于对当前类加锁,进入同步方法前获得当前类的锁。
对于上面的1、2.必须是同一对象或者同一实例时才会使线程阻塞。
锁是加在对象实例上的。加在不同对象上的锁是不会相互影响的。两个线程访问两个不同对象,是不会相互阻塞的。