重入锁的学习 (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();
    }
}

相关文章
相关标签/搜索