Java中ReentrantLock锁的尝试锁,可中断锁,公平锁讲解与实例代码

前言

通过代码实例,展示ReentrantLock的使用和常用属性,展示运行结果,方便理解。
提示:最好可以根据演示实例,自己手动写一下,有的时候写一下会自己发现并解决很多细节问题


ReentrantLock

ReentrantLock 是synchronized锁之后出现的,不是java原生的锁,写在jar包中。
ReentrantLock必须手动释放锁。
可以用来完全替代synchronized锁,并提供了一些synchronized没有提供的方法。如下

tryLock

尝试锁,执行tryLock的时候并不会直接将线程锁上,还是尝试获取锁,如果获取不到。并不会让线程进入到阻塞状态
tyrLock(时间,时间单位 TimeUtil.SECONDS/TimeUtil.MILLISECONDS );

package ReentrantLockLongAdder;

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

/**
 * @program: solution
 * @description: 模拟tryLock使用
 * @author: Wang Hai Xin
 * @create: 2022-11-08 11:55
 **/
public class ReentrantLockT {
    ReentrantLock Lock = new ReentrantLock();

    void m1() {
        try {
            Lock.lock();

            for (int i = 0; i < 10; i++) {
                /*
                * TimeUnit是java.util.concurrent包下的一个类名
主要功能是暂停线程的操作
与Thread.sleep()一样的功能都是暂停线程
                * */
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            Lock.unlock();
        }
    }

    void m2() {
        boolean sgin = false;
        try {
            sgin = Lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2 lock:" + sgin);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            if (sgin) {
                Lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockT T = new ReentrantLockT();
        new Thread(T::m1,"T1").start();
        TimeUnit.SECONDS.sleep(1);

        new Thread(T::m2,"T2").start();
    }
}

运行结果

0
1
2
3
4
m2 lock:false
5
6
7
8
9

lockInterrupt 可响应锁

Interrupt 正常只可以中断获取锁的线程,不可以中断处于阻塞状态的线程。
lockInterrupt 可中断锁,当T0使用IockInterrupt获取锁时,
T1通过lockInterrupt获取锁处于阻塞状态时,也可以通过interrupt中断阻塞

代码如下(示例):

package ReentrantLockLongAdder;

import 线程同步volatile单例.T;

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

/**
 * @program: solution
 * @description: 模拟interrupt可响应锁
 * @author: Wang Hai Xin
 * @create: 2022-11-09 10:43
 **/
public class InterruptT {

    private Lock lock = new ReentrantLock();

    public void doBussiness() {
        String name = Thread.currentThread().getName();

        try {
            System.out.println(name + " 开始获取锁");
            lock.lockInterruptibly();
            System.out.println(name + " 得到锁");
            System.out.println(name + " 开工干活");
            for (int i=0; i<5; i++) {
                Thread.sleep(1000);
                System.out.println(name + " : " + i);
            }
        } catch (InterruptedException e) {
            System.out.println(name + " 被中断");
            System.out.println(name + " 做些别的事情");
        } finally {
            try {
                lock.unlock();
                System.out.println(name + " 释放锁");
            } catch (Exception e) {
                System.out.println(name + " : 没有得到锁的线程运行结束");
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {

        InterruptT lockTest = new InterruptT();

        Thread t0 = new Thread(
                new Runnable() {
                    public void run() {
                        lockTest.doBussiness();
                    }
                }
        );

        Thread t1 = new Thread(
                new Runnable() {
                    public void run() {
                        lockTest.doBussiness();
                    }
                }
        );

        // 启动线程t1
        t0.start();
        Thread.sleep(10);
        // 启动线程t2
        t1.start();
        Thread.sleep(100);
        // 线程t1没有得到锁,中断t1的等待
        t0.interrupt();
    }
}

运行结果

Thread-0 开始获取锁
Thread-0 得到锁
Thread-0 开工干活
Thread-1 开始获取锁
Thread-0 被中断
Thread-0 做些别的事情
Thread-0 释放锁
Thread-1 得到锁
Thread-1 开工干活
Thread-1 : 0
Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-1 释放锁

进程已结束,退出代码0


t1.interrupt(); 当我们中断处于等待线程的t1 。运行结果

Thread-0 开始获取锁
Thread-0 得到锁
Thread-0 开工干活
Thread-1 开始获取锁
Thread-1 被中断
Thread-1 做些别的事情
Thread-1 : 没有得到锁的线程运行结束
Thread-0 : 0
Thread-0 : 1
Thread-0 : 2
Thread-0 : 3
Thread-0 : 4
Thread-0 释放锁

进程已结束,退出代码0


lock.lock(); 将锁换成lock锁,运行结果

Thread-0 开始获取锁
Thread-0 得到锁
Thread-0 开工干活
Thread-1 开始获取锁
Thread-0 : 0
Thread-0 : 1
Thread-0 : 2
Thread-0 : 3
Thread-0 : 4
Thread-0 释放锁
Thread-1 得到锁
Thread-1 开工干活
Thread-1 被中断
Thread-1 做些别的事情
Thread-1 释放锁

进程已结束,退出代码0


公平锁

在创建ReentrantLock时 传入 true,则表示公平锁

公平锁,则表示所有线程过来之后按照顺序执行,而非公平锁是谁抢到锁谁执行。公平锁的效率要比非公平锁效率低很多。

package ReentrantLockLongAdder;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: solution
 * @description: 公平锁和非公平锁
 * @author: Wang Hai Xin
 * @create: 2022-11-09 11:29
 **/
public class ReentrantLockT1 {

    /*true 为公平锁*/
    ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        ReentrantLockT1 t = new ReentrantLockT1();
        Thread t1 = new Thread(t::solution, "t1");
        Thread t2 = new Thread(t::solution, "t2");
        Thread t3 = new Thread(t::solution, "t3");
        Thread t4 = new Thread(t::solution, "t4");
        Thread t5 = new Thread(t::solution, "t5");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }

    public void solution() {
        String name = Thread.currentThread().getName();
        try {
            lock.lock();
            System.out.println(name + "得到了锁");
        } finally {
            lock.unlock();
        }
    }
}

运行结果

t1得到了锁
t2得到了锁
t5得到了锁
t4得到了锁
t3得到了锁
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑白极客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值