基于CAS的一些锁(1)- ReentrantLock

synchronized的可重入性

如果一个同步方法m1中调用了另一个同步方法m2,并且这两个方法加的是同一把锁。那么在一个线程调用m1时就得到了这把锁,m1中调m2时发现是同一个线程,m2也能得到这把锁。这是锁的可重入。

所谓可重入锁就是拿到这把锁之后可以再加多道锁,但锁定的还是同一对象,被嵌套调用的同步方法执行完就去一道。

public class SyncTest_03 {

    public synchronized void m1() {
        System.out.println("m1 start");
        m2(); // m2的第二道锁被释放后才继续往下执行
        System.out.println("m1 end");
    }

    public synchronized void m2() {
        System.out.println("m2");
    }

    public static void main(String[] args) {
        SyncTest_03 syncTest03 = new SyncTest_03();
        new Thread(syncTest03::m1).start();

    }
}
  • 模拟子类同步方法调用父类同步方法:
    注:子类和父类是同一把锁
public class SyncTest_04 {

    public synchronized void m() {
        System.out.println("m start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m end");
    }

    public static void main(String[] args) {
        Child child = new Child();
        new Thread(child::m).start();
    }
}

class Child extends SyncTest_04 {
    @Override
    public synchronized void m() {
        System.out.println("child m start");
        super.m(); // 调用父类是同一把锁
        System.out.println("child m end");
    }
}

ReentrantLock

ReentrantLock可以替代synchronized,需把原来synchronized的地方换成lock.lock(),加完锁还需要手动解锁lock.unlock(),并且要在try...finally中手动解锁,保证程序执行完或异常后能释放锁。synchronized是自动解锁的。

public class T01_ReentrantLock {

    Lock lock = new ReentrantLock();

    public void m1() {
        try {
            lock.lock(); // synchronized(this)
            System.out.println("m1 start");
            m2(); // m2的第二道锁被释放后才继续往下执行
            System.out.println("m1 end");
        } finally {
            lock.unlock(); // 解锁
        }
    }

    public void m2() {
        try {
            lock.lock();
            System.out.println("m2");
        } finally {
            lock.unlock(); // 解锁
        }
    }

    public static void main(String[] args) {
        T01_ReentrantLock instance = new T01_ReentrantLock();
        new Thread(instance::m1).start();
    }
}

既然ReentrantLock与synchronized都可重入,那ReentrantLock有什么用?

tryLock()

ReentrantLock当然还有特别的功能,可以使用tryLock进行尝试锁定不管锁定与否,方法都将继续执行。lock.tryLock()返回boolean类型。
synchronized如果锁定失败就阻塞了,但是用ReentrantLock可以自己决定要不要wait。

public class T01_ReentrantLock1 {

    Lock lock = new ReentrantLock();

    public void m1() {
        try {
            lock.lock(); // synchronized(this)
            System.out.println("m1 start");
            TimeUnit.SECONDS.sleep(7);
            System.out.println("m1 end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void m2() {
        boolean locked = false;
        try {
            // locked = lock.tryLock();
            locked = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2..." + locked);
        }  catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (locked) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        T01_ReentrantLock1 instance = new T01_ReentrantLock1();
        new Thread(instance::m1).start();
        new Thread(instance::m2).start();
    }
}

m1、m2 start,m1先睡7s,m2 tryLock 5s,此时锁还没被m1释放,tryLock返回false。若m1睡4s,释放锁后m2 tryLock返回true。

lockInterruptibly()

ReentrantLock可以用 lock.lockInterruptibly(),对interrupt()方法做出响应。

线程在请求lock并被阻塞时,如果被interrupt,则此线程会被唤醒并被要求处理InterruptedException。并且如果线程已经被interrupt,再使用lockInterruptibly的时候,此线程也会被要求处理interruptedException.

若此线程在运行中没有阻塞, 则不会处理interruptedException。但此线程的 “打断标志”会被设置, 可通过isInterrupted()查看并作出处理。

public class T01_ReentrantLock2 {

    Lock lock = new ReentrantLock();

    public void m1() {
        try {
            lock.lock(); // synchronized(this)
            System.out.println("m1 start");
            TimeUnit.SECONDS.sleep(10);
            System.out.println("m1 end");
        } catch (InterruptedException e) {
            System.out.println("Interrupted!!");
        } finally {
            lock.unlock();
        }
    }

    public void m2() {
        boolean locked = false;
        try {
            lock.lockInterruptibly(); // 可以对interrupt()方法做出响应
            System.out.println("m2 start");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("m2 end");
        }  catch (InterruptedException e) {
            System.out.println("m2 Interrupted!!");
        } finally {
            if (locked) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        T01_ReentrantLock2 instance = new T01_ReentrantLock2();
        Thread t1 = new Thread(instance::m1);
        Thread t2 = new Thread(instance::m2);
        t1.start();
        t2.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt(); // 打断线程2的等待
    }

}
公平锁与非公平锁
  • 什么是公平锁与非公平锁?
    如果是公平锁,一个线程会先检查等待队列里是否有其它线程,如果有进入队列排队,等别的线程先运行;
    如果是非公平锁,一个线程不管其它线程是否先执行,而是上来就竞争锁。

ReentrantLock默认是非公平锁,但是可指定为公平锁。

// 参数为true是公平锁
ReentrantLock lock = new ReentrantLock(true);

总结

  • ReentrantLock可以替代synchronized,也可重入,底层是cas
  • tryLock:尝试锁定,不管锁定与否,都将继续执行。tryLock()返回boolean类型
  • lockInterruptibly:被interrupt()后,线程会被唤醒并被要求处理InterruptedException
  • ReentrantLock默认为非公平锁,new ReentrantLock(true) 设置为公平锁
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。