Java is not the exclusive lock lock unfair understand

Java tutorial series of exclusive lock lock

Concurrent programming in Java, the lock is a very important subject. There are two locks in Java: implicit and explicit lock lock. Use the synchronized keyword lock is implicit lock. Because the application and release locks are made to maintain the JVM, we do not have to manually process. Use Java and contracting under the locks lock bag, and requires the user to manually apply manually closed. This form is an explicit lock. If you follow multiple threads can not share the same lock (resources) to points, then, it can be divided into exclusive (exclusive) locks and shared locks. ReentrantLock lock which locks and lock the synchronized keyword are exclusive lock.

Through the study of the previous three articles, we know that the base frame synchronization component -AbstractQueuedSynchronizer (AQS) synchronizer. There are two ways to acquire the lock in the process of the synchronizer: shared and exclusive locks. Let's learn exclusive lock -ReentrantLock.

Benpian is: Part IV "Lock Series" tutorials "Kaige (Kaige Java kagejava) Concurrent Programming Learning" Series: "Java contract under lock and learning Part IV: ReentrantLock".

0fc7UKllQ9o

edit

ReentrantLock using the syntax

We know that under the contract and is explicitly lock the lock, you need to manually acquire the lock and manually release the lock. So syntax is as follows:

ReentrantLock lock = new ReentrantLock();

try {

lock.lock();

//ALL

}finally {

lock.unlock();


}

Acquire a lock: lock.lock ();

Release the lock: lock.unlock ();

Try to get in lock; the lock is released finally in.

Because it is necessary to release the lock. Therefore, it must release the lock operation is finally in. Lock and release operations must be placed on the first line finally.

Exclusive lock understand:

Life examples:

在自动ATM机上取钱的时候,我们需要排队,当一个人在操作ATM机取钱的时候,下一个人就需要在ATM机黄线外面等待(排除和取钱人一起去的人)。假设路人甲在操作ATM机的时候,我们其他后面排队的人是不是需要等待着,路人甲从ATM机区域出来后才可以进行操作ATM机。这个操作过程如果放在我们多线程并发角度来思考的话:共享数据是ATM机,多个线程是多个存取钱的人。当路人甲在操作ATM机的时候路人甲获取到ATM机操作权限可以理解为lock.lock()操作。这个时候,共享数据ATM机就会被路人甲独自一个人占用了(独占式获取到了共享数据(或者是锁))。当路人甲操作完离开ATM机这个操作可以理解为lock.unlock()操作。

从上了生活例子中我们可以这么理解独占式锁,所谓的独占式锁就是同一时刻只能有且只有一个线程获取到锁且操作成功,其他线程只能等待释放锁后,在进行操作。

需要说明的是,在Java中隐式锁(synchronized关键字修饰的)也是独占式锁的一种体现。

使用方法一:独占非公平演示

需求:使用三个线程,调用一个方法,在方法内睡眠2s.代码下图:

0fc7UNtwOQK


查看运行结果:

线程2开始获取锁。

线程3开始获取锁。

线程1开始获取锁。

线程2获取到了锁。开始做其他的操作了====do..........

======关闭锁=======

线程3获取到了锁。开始做其他的操作了====do..........

======关闭锁=======

线程1获取到了锁。开始做其他的操作了====do..........

======关闭锁=======

0fc7UOKR1VI


从上图运行结果,我们可以分析出:

1:线程的顺序和我们线程运行的顺序不一致

2:每次只能有一个线程执行完关闭锁之后,其他线程才可以接着使用。

从示例代码,我们可以得到如下总结:

1:reentrantLock是独占式锁;

2:默认情况下不能保证获取锁的顺序和线程执行顺序的一致性。

如果想要保证线程执行顺序和获取锁的顺序一致性,也是可以操作的。在下一篇文章中,凯哥将讲解怎么操作。

wx.jpg

                                                            Welcome to chat



Guess you like

Origin blog.51cto.com/kaigejava/2484634