What event will make a waiting thread execute a synchronized method already run by another thread?

Cesare :

In Java programming, if I have a thread A blocked when it tries to execute a synchronized method of the same object that another thread B is executing, what event will make it possible for the thread A to execute the synchronized method?

Is the simple fact that the thread B has finished executing the method enough for the thread A to step in from his waiting state and execute the method? Or do I need to call the notifyAll or notify somewhere in the synchronized method?

Jean-Baptiste Yunès :

Java Tutorial says:

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.

Java Language Reference says (emphasize's mine):

8.4.3.6. synchronized Methods

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

17.1. Synchronization

The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.

The synchronized statement (§14.19) computes a reference to an object; it then attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed. After the lock action has been performed, the body of the synchronized statement is executed. If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.

14.19. The synchronized Statement

A synchronized statement acquires a mutual-exclusion lock (§17.1) on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161029&siteId=1