The Locksupport class is a class introduced by JAVA6 (JSR166-JUC) and provides a basic thread synchronization primitive. Locksupport actually calls the function in the unsafe class, which comes down to the unsafe, with only two functions:
[Java] view plaincopy
-
public native void
Public native voidPark (BooleanIsabsolute,LongTime );
The Isabsolute parameter indicates whether the time is absolute or relative.
With just two simple interfaces, it provides a powerful synchronization primitive for the upper layer.
First to parse the next two functions is what to do.
The Unpark function provides a "license (permit)" for the thread, and the thread calls the park function to wait for a "license." This is a bit like a semaphore, but this "license" is not superimposed, "licensing" is a one-time.
For example, thread B calls three consecutive Unpark functions, and when thread A calls the park function to use the "license", if thread A calls park again, it goes to the waiting state.
Note that the Unpark function can be called before park. For example, thread B calls the Unpark function and sends a "license" to thread A, so when thread A calls park, it discovers that it already has a "license", then it will continue to run immediately.
In fact, even if the park function is not "licensed", it sometimes returns for no reason, and this is resolved.
The flexibility of park and Unpark
As mentioned above, the Unpark function can be called before Park, which is where they are flexible.
One thread it might be before another thread unpark, or after, or call park at the same time, because of Park's features, it can not worry about the timing of their own park, otherwise, if Park must be in Unpark before, then to programming a lot of trouble!!
Consider how to handle two threads in sync.
In the JAVA5 is used Wait/notify/notifyall to synchronize. Wait/notify mechanism There is a very painful place, such as thread B to use notify to notify thread A, then thread B to make sure that thread A has been waiting on the wait call, or thread A May always wait. It hurts when you're programming.
In addition, is it called notify, or Notifyall?
Notify only wakes up one thread, and if there are two threads incorrectly waiting on the same object wait, then it's tragic. For security reasons, it seems that only notifyall can be called.
The Park/unpark model truly decouples synchronization between threads, eliminating the need for an object or other variable to store state between threads, no longer needing to care about each other's state.
Java Locksupport.park () implementation analysis