Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

1. Introduction

At the bottom of AQS, we understand the internal structure of the whole AQS, and the realization of its exclusive and shared access to synchronous state. However, it does not describe in detail how threads block and wake up. I also mentioned that these operations of the thread are related to the LockSupport utility class. Now let’s explore the implementation of this class.

2. LockSupport class

LockSupport static method class, the following blocking thread and wake up thread divide methods into two classes:

  • Park – Blocks the thread

    methods instructions
    park() Blocks the current thread, which can be returned from the park() method if the unpark method is called or the current thread is interrupted
    park(Object blocker) Blocking the current thread takes the same Object argument as the park() method. It is used to record the blocking object that causes the thread to block, which is convenient for troubleshooting
    parkNanos(long nanos) Blocks the current thread for up to nanos nanoseconds, added a timeout return feature
    parkNanos(Object blocker, long nanos) ParkNanos (Long Nanos) adds an Object to the argument, which records the blocking Object that causes the thread to block.

    Facilitate troubleshooting
    parkUntil(long deadline) Blocks the current thread until the deadline
    parkUntil(Object blocker, long deadline) Add an Object to the parkUntil(long Deadline) function, which records the blocking Object that causes the thread to block.

    Facilitate troubleshooting

    Tips: The above six methods can be divided into two groups into three groups

    • Park () and Park (Object Blocker) — block the current thread indefinitely
    • ParkNanos (Long Nanos) and parkNanos(Object Blocker, Long Nanos) – Adds blocks up to a maximum nanOS duration
    • ParkUntil (Long Deadline) and parkUntil(Object Blocker, Long Deadline) – Add deadline time blocking
  • Unpark – Wakes up the thread

    methods instructions
    unpark(Thread thread) Wakes up the specified thread in the blocked state

3. Code demonstration

Code the above method.

Park (3.1)

3.2 park (Object blocker)

3.3 parkNanos (long nanos)

3.4 parkNanos(Object blocker, long nanos)

3.5 parkUntil (long deadline)

3.6 parkUntil(Object blocker, long deadline)

4. Difference between parameters with Object and none

First look at the code:

Then use the Java command to see the difference

I am ant back elephant, the article is helpful to you like to pay attention to me, the article has incorrect place please give correct comments ~ thank you