Object.wait()

Before wait() is performed, Synchronized code blocks compete for Synchorized, and the bytecode generated by javap contains monitorenter and Monitorexit instructions. Monitorenter directive monitorenter directive monitorenter directive Monitorenter directive Monitorenter directive Monitorenter directive Monitorenter directive Monitorenter directive Monitorenter The monitor object must also be held when lock.wait () is executed.

LockSupport.park()

Action object

After all, the native code in the Unsafe call to LockSupport:

public native void unpark(Thread jthread); 
public native void park(boolean isAbsolute, long time); 
Copy the code

Two function declarations clearly specify the object to operate on:

The park function blocks the current Thread, and the unpark function wakes up another Thread.

Compared with the wait/notify mechanism of Object, park/unpark has two advantages:

  1. Using thread as the operation object is more consistent with the intuitive definition of blocking threads.
  2. The operation is more precise and can wake up a thread exactly (notify randomly wakes up one thread, notifyAll wakes up all waiting threads), increasing flexibility.

About the license

In the above text, I used blocking and wake to contrast with wait/notify. In fact, the core design principle of Park/Unpark is “permission”. Park is waiting for a permit. Unpark provides a license for a thread. If thread A calls park, thread A will block on the park operation unless another thread calls unpark(A) to give A permission.

One thing that is difficult to understand is that the unpark operation can precede the park operation. In other words, give permission first. When a thread calls Park and already has permission, it consumes the permission and can continue running. It’s a must.

Consider the simplest Producer Consumer model:

The Consumer needs to consume a resource and calls the park operation to wait;

The Producer produces the resource and then calls unpark to give the Consumer permission to use it.

It is quite possible that the Producer produces first, and the Consumer may not have been constructed (for example, the thread hasn’t been started or switched to that thread). So when the Consumer is ready to consume, obviously the resource has been produced and can be used directly, then of course the park operation can be run directly. Without this semantics, it would be very difficult to manipulate. Scan the QR code to follow the public account “Ape Must Pass”

Answer the “interview questions” and collect them yourself.

Wechat group for discussion, please add wechat account: zyhui98, note: interview questions add group

This article is published by YBG. Unauthorized reprint is prohibited. Violators are subject to legal liability