The previous sections mainly talk about atomic operations. As for some problems or traps related to atomic operations, they will be explained in the final summary. Starting from this chapter, we will spend a small amount of time talking about the lock mechanism.
In the previous chapter, we talked about the lock mechanism and some related concepts and design ideas for atomic operations. In the next article, we will try our best to study the lock mechanism in depth and understand the principles and practical application scenarios.
Although synchronized is simple enough in syntax, it can only be used before JDK 5, but because it is an exclusive lock, its performance is not high, therefore, JDK 5 and later began to use JNI to implement more advanced lock implementation.
The lock in JDK 5 is an interface.Java. util. concurrent. locks. Lock. In additionJava. util. concurrent. locks. ReadWriteLockProvides a pair of locks for read/write concurrency. According to the preceding rulesJava. util. concurrent. locks. Lock.
Void lock ();
Obtain the lock.
If the lock is unavailable, the current thread is disabled for Thread Scheduling and remains in sleep state until the lock is obtained.
Void lockInterruptibly () throws InterruptedException;
If the current thread is not interrupted, the lock is obtained.
If the lock is available, the lock is obtained and immediately returned.
If the lock is unavailable, the current thread is disabled for Thread Scheduling and remains in sleep state until one of the following conditions occurs:
- The lock is obtained by the current thread; or another thread interrupts the current thread and supports the interruption of the lock.
If the current thread:
- The thread interruption status has been set when you enter this method; or the thread is interrupted when the lock is obtained and the thread can be interrupted when the lock is obtained.
InterruptedException
And clear the interrupted status of the current thread.Condition newCondition ();
Bind to thisLock
New instanceCondition
Instance. The next section will focus on Condition, which is not described too much here.
Boolean tryLock ();
The lock is obtained only when the lock is idle.
If the lock is available, the lock is obtained and the returned value is immediately.true
. If the lock is unavailable, this method returns the value immediately.false
.
It is usually useful for operations that do not have to obtain the lock.
Boolean tryLock (long time, TimeUnit unit) throws InterruptedException;
If the lock is idle within the specified waiting time and the current thread is not interrupted, the lock is obtained.
If the lock is available, this method returns the value immediately.true
. If the lock is unavailable, the current thread is disabled for Thread Scheduling purposes and remains in sleep state until one of the following three conditions occurs: