重入锁的学习 (ReentrantLock)

重入锁  :(ReentrantLock)

  • 上锁 用reentrantLock.lock 方法 解锁 用reentrantLock.unlock 方法
  • 上锁和解锁 必须配对 可以多重上锁
  • ReentrantLock 是对 synchronized 的升级,synchronized 底层是通过 JVM 实现的,
  • ReentrantLock 是通过 JDK 实现的,使⽤起来更加简单。
  • 重⼊锁是指可以给同⼀个资源添加过个锁,并且解锁的⽅式与 synchronized 有区别,
  • synchronized 的锁是线程执⾏完毕之后⾃动释放,ReentrantLock 的锁是通过开发者⼿动释放的。
import java.util.concurrent.locks.ReentrantLock;

public class Account implements Runnable {
    private static int num;
    private ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
//上锁
        reentrantLock.lock();
        reentrantLock.lock();
        num++;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("您是第" + num + "位访客");
//解锁
        reentrantLock.unlock();
        reentrantLock.unlock();
    }
}

 

public class Test {
    public static void main(String[] args) {
        Account account = new Account();
        new Thread(account).start();
        new Thread(account).start();
    }
}

 

  • 重⼊锁可中断,是指某个线程在等待获取锁的过程中可以主动终⽌线程,lockInterruptibly()。
  • 重⼊锁具备限时性的特点,可以判断某个线程在⼀定的时间内能否获取锁。
  • boolean tryLock(long time,TimeUnit unit) time:时间数值 unit:时间单位
  • true 表示在该时段内能够获取锁,false 表示在该时段内⽆法获取锁。
  • 当判断的时间小于休眠的时间时不能获取锁 否则可以
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class TimeOut implements Runnable {
    private ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
        try {
            if (reentrantLock.tryLock(6, TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName() + "get lock");
                Thread.sleep(5000);
            } else {
                System.out.println(Thread.currentThread().getName() + "not lock");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        reentrantLock.unlock();
    }
}

 

public class Test01 {
    public static void main(String[] args) {
        TimeOut timeOut = new TimeOut();
        new Thread(timeOut,"线程1").start();
        new Thread(timeOut,"线程2").start();
    }
}

 

posted @ 2019-08-05 10:26  善感不多愁  阅读(193)  评论(0编辑  收藏  举报