ReentrantLock and synchronized summary

I. Introduction
ReentrantLock often contrast with synchronized analysis, we compare the first term and then little by little analysis.
(1) synchronized is an exclusive lock, locking and unlocking process automatic, easy to operate, but less flexible. ReentrantLock also exclusive lock, locking and unlocking process is manual, easy to operate, but very flexible.
(2) synchronized reentrant, because the lock and unlock automatically, without worrying about whether the final release of the lock; ReentrantLock also reentrant, but require manual locking and unlocking, and the number to be the same, or other threads can not get a lock.
(3) synchronized not interrupt response, a thread can not acquire the lock has been waiting for; ReentrantLock can the corresponding interrupt.
ReentrantLock did not seem much better than the synchronized keyword, we could look at that are not synchronized, the most important is a ReentrantLock can achieve fairness locking mechanism. What is fair lock it? That is locked threads waiting the longest will get the right to use the lock. Who is the popular understanding of who should perform the longest queue to obtain a lock.

Two: ReentrantLock additional features compared to the synchronized

Fair lock means that when the lock is available, thread lock waiting the longest will get the right to use the lock. Rather than fair lock then randomly assigned to use this right. And synchronized as a non-default ReentrantLock achieve fair locks, as compared to fair better locks, lock unfair performance. Of course, fair locks to prevent hunger and in some cases also useful. Created when creating ReentrantLock through pass into the lock fair argument true, if the incoming transmission parameters is false or not lock the creation of non-equity

static Lock lock = new ReentrantLock(true);

Code as follows:

public class ReentrantLockTest {

    static Lock lock = new ReentrantLock(true);

    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<5;i++){
            new Thread(new ThreadDemo(i)).start();
        }
    }

    static class ThreadDemo implements Runnable {
Integer id;
public ThreadDemo(Integer id) { this.id = id; } @Override public void run() { try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } for(int i=0;i<2;i++){ lock.lock(); System.out.println("获得锁的线程:"+id); lock.unlock(); } } } }

Run results are shown below:

获得锁的线程:4
获得锁的线程:1
获得锁的线程:2
获得锁的线程:0
获得锁的线程:3
获得锁的线程:4
获得锁的线程:1
获得锁的线程:2
获得锁的线程:0
获得锁的线程:3

非公平锁运行结果如下所示:

获得锁的线程:1
获得锁的线程:1
获得锁的线程:2
获得锁的线程:2
获得锁的线程:3
获得锁的线程:3
获得锁的线程:4
获得锁的线程:0
获得锁的线程:0
获得锁的线程:4

线程会重复获取锁。如果申请获取锁的线程足够多,那么可能会造成某些线程长时间得不到锁。这就是非公平锁的“饥饿”问题。
公平锁和非公平锁该如何选择:
大部分情况下我们使用非公平锁,因为其性能比公平锁好很多。但是公平锁能够避免线程饥饿,某些情况下也很有用。

 

Guess you like

Origin www.cnblogs.com/jelly12345/p/12446902.html