java 中的线程和锁

Threading & locks in java

我听说 java 中的每个对象都有一个与之关联的内部锁。如果一个线程拿这个锁来调用同步方法怎么办。这是否意味着没有其他线程可以访问此对象中的任何方法或只能访问同步方法?!

只有一个线程可以同时访问同步方法。

official documentation:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

synchronized 在实例方法上是 shorthand 对于 synchronized (this) { } 围绕整个方法主体。对于静态方法,它相当于 synchronized (this.class) { }。所以想想 synchronized (obj) { }.

只有一个线程可以获得锁,所以从表面上看,一次只能有一个线程进入。输家线程 阻塞 直到锁可用。

这还不是全部。如果在 synchronized 块中的某处(可能在另一个方法中)线程调用 this.wait();(带有可选参数),那么该线程会在 wait() 期间释放锁。在此期间,锁可用,例如,调用 this.notifyAll().

另外值得注意的是锁是可重入的。可以递归调用另一个或相同的 synchronized 方法。