java公平锁/非公平锁/可重入锁/递归锁/自旋锁/独占锁/共享锁

一、公平和非公平锁

公平锁:多个线程按照申请锁的顺序来获取锁,类似排队打饭,先来后到

非公平锁:是指多个线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取锁

在高并发情况下,有可能会造成优先级反转或者饥饿现象。

 

并发包中ReentrantLock的创建可以指定构造函数的Boolean类型来得到公平锁或非公平锁,默认是非公平锁,源码分析:

    //new ReentrantLock()的底层代码,默认不传值为false(非公平锁)
    //如果//new ReentrantLock(true)则为公平锁

    /**
     * Creates an instance of {@code ReentrantLock}.
     * This is equivalent to using {@code ReentrantLock(false)}.
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * Creates an instance of {@code ReentrantLock} with the
     * given fairness policy.
     *
     * @param fair {@code true} if this lock should use a fair ordering policy
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

两者的区别:

公平锁:Threads acquire a fair lock in the order in which they requested it

公平锁,就是很公平,在并发环境中,每个线程在获取锁时会先查看维护此锁的等待队列,如果为空,或者当前线程是等待队列的第一个,就占有锁,否则会加入到等待队列中,以后会按照FIFO的规则从队列中取到自己。

非公平锁:a nonfair lock permits barging:threads requesting a lock can jump ahead of the queue of waiting threads if the lock happens to be avaiable when it is requested.

非公平锁比较粗鲁,上来就直接尝试占有锁,如果尝试失败,就再采用类似公平锁那种方式。

java ReentrantLock而言

通过构造函数指定该锁是否是公平锁,默认是非公平锁。非公平锁的优点在于吞吐量比公平锁大。

对于Synchronized而言,也是一种非公平锁。

二、可重入锁(又名递归锁)

指的是同一线程外层函数获取锁之后,内层递归函数仍然能够获取该锁的代码,在同一线程在外层方法获取锁的时候,在进入内层方法会自动获取锁

也就是说:线程可以进入任何一个她已经拥有的锁所同步的代码块。

RenntrantLock/Synchronized就是典型的可重入锁

可重入锁最大的作用就是避免死锁

    /**
     * 可以简单的理解method()和method1()两者获取的是同一把锁
     */
    public synchronized void method() {
        method1();
    }
    public synchronized void method1() {

    }
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: YongXuezhen
 * @Date: 2019/5/16 12:28
 * @Description: 可重入锁(递归锁)
 */
class Phone implements Runnable {
    public synchronized void sendSMS() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\t invoked sendSMS()");
        sendSmail();
    }

    public void sendSmail() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\t ==========invoked sendEmail()");
    }

    //========================================================================================
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        get();
    }

    public void get() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t invoked get()");
            set();
        } finally {
            lock.unlock();
        }
    }

    public void set() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t ===== invoked set()");
        } finally {
            lock.unlock();
        }
    }

}

/**
 * t1	 invoked sendSMS() t1 线程在外层方法获取锁的时候
 * t1	 ==========invoked sendEmail() t1线程在进去内层方法会自动获取锁
 * t2	 invoked sendSMS()
 * t2	 ==========invoked sendEmail()
 */
public class ReenterLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(() -> {
            try {
                phone.sendSMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t1").start();
        new Thread(() -> {
            try {
                phone.sendSMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t2").start();
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        Thread t3 = new Thread(phone, "t3");
        Thread t4 = new Thread(phone, "t4");
        t3.start();
        t4.start();
    }
}

上述代码输出:

t1     invoked sendSMS()
t1     ==========invoked sendEmail()
t2     invoked sendSMS()
t2     ==========invoked sendEmail()


t3     invoked get()
t3     ===== invoked set()
t4     invoked get()
t4     ===== invoked set()

三、自旋锁

自旋锁(spinlock)

是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。

例如:CAS中unsafe类中getAndAddInt方法

    public final int getAndAddInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

        return var5;
    }

Demo如下:

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Auther: YongXuezhen
 * @Date: 2019/5/16 16:17
 * @Description:
 */
public class SpinLockDemo {
    //原子引用线程
    AtomicReference atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t come in ");
        while (!atomicReference.compareAndSet(null, thread)) {
            //System.out.println(Thread.currentThread().getName() +"\t jin");
        }
    }

    public void myUnLock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t invoked myUnLock() ");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            spinLockDemo.myLock();
            try {TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) {e.printStackTrace();}
            spinLockDemo.myUnLock();
        },"AA").start();

        try {TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {e.printStackTrace();}

        new Thread(()->{
            spinLockDemo.myLock();
            try {TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {e.printStackTrace();}
            spinLockDemo.myUnLock();
        },"BB").start();

    }
}

输出结果

AA     come in 
AA     invoked myUnLock() 
BB     come in 
BB     invoked myUnLock() 

四、独占锁和共享锁

独占锁:指该锁一次只能被一个线程锁持有。对ReentrantLock和Synchronized而言都是独占锁

共享锁:指该锁可以被多个线程所持有

对ReentrantReadWriteLock其读锁是共享锁,其写锁是独占锁

读锁的共享锁可保证并发读是非常高效的,读写,写读,写写的过程是互斥的。

 

 

 

 

 

 

 

你可能感兴趣的:(学习)