各种锁的理解

各种锁的理解

  • 公平锁、非公平锁

    公平锁: 非常公平, 不能够插队,必须先来后到!

    非公平锁:非常不公平,可以插队 (默认都是非公平)

public ReentrantLock() {
    sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}
//默认都是非公平锁
  • 可重入锁

    可重入锁(递归锁)

    在这里插入图片描述

    Synchronized版

    public class Test01 {
        public static void main(String[] args) {
            Phone phone = new Phone();
            new Thread(() -> {
                phone.sms();
            }, "A").start();
            new Thread(() -> {
                phone.sms();
            }, "B").start();
        }
    }
    
    class Phone {
        public synchronized void sms() {
            System.out.println(Thread.currentThread().getName() + "sms");
            call(); // 这里也有锁
        }
    
        public synchronized void call() {
            System.out.println(Thread.currentThread().getName() + "call");
        }
    }
    

    Lock 版

    public class Test01 {
        public static void main(String[] args) {
            Phone phone = new Phone();
            new Thread(() -> {
                phone.sms();
            }, "A").start();
            new Thread(() -> {
                phone.sms();
            }, "B").start();
        }
    }
    
    class Phone {
        Lock lock = new ReentrantLock();
    
        public void sms() {
            lock.lock(); // 细节问题:lock.lock(); lock.unlock(); // lock 锁必须配对,否 则就会死在里面
            try {
                System.out.println(Thread.currentThread().getName() + "sms");
                call(); // 这里也有锁
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    
        public void call() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "call");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    
posted @ 2021-05-05 13:50  saxon宋  阅读(83)  评论(0)    收藏  举报