当前位置: 首页 > news >正文

java ReentrantLock

介绍

ReentrantLock称为重入锁,比内部锁synchonized拥有更强大的功能,它可中断、可定时、设置公平锁

【注】使用ReentrantLock时,一定要释放锁,一般释放放到finnal里写。

提供以下重要的方法

  • lock():获得锁,如果锁已被占用,则等待
  • lockInterruptibly():获得锁,但有限响应中断
  • unlock():释放锁
  • tryLock():尝试获取锁。如果获得,返回true;否则返回false
  • tryLock(long time, TimeUnit unit):在给定时间内获得锁。如果获得返回true;否则返回false

示例

例子1

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    ReentrantLock lock;

    ReentrantLockTest(ReentrantLock lock) {
        this.lock = lock;
    }

    private Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        if (lock.tryLock()) {
                            try {
                                System.out.println("Locked:" + Thread.currentThread().getName());
                                Thread.sleep(800);
                            } finally {
                                lock.unlock();
                                System.out.println("UnLocked:" + Thread.currentThread().getName());
                            }
                            System.out.println("break before");
                            break;
                        } else {
                            //System.out.println("Unable to lock " + Thread.currentThread().getName());
                        }

                    } catch (InterruptedException e){
                        System.out.println(Thread.currentThread() + " is Interupted");
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        ReentrantLockTest test = new ReentrantLockTest(lock);
        ReentrantLockTest test2 = new ReentrantLockTest(lock);
        Thread thread1 = new Thread(test.getRunnable(), "firstThread");
        Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

        thread1.start();
        thread2.start();
        try {
            Thread.sleep(300);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("interupt begin");
        thread2.interrupt();
        System.out.println("interupt end");
    }
}

一次执行结果:

Locked:firstThread
interupt begin
interupt end
UnLocked:firstThread
break before
Locked:secondThread
UnLocked:secondThread
Thread[secondThread,5,main] is Interupted
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.jihite.templet.JavaBase.ReentrantLockTest$1.run(ReentrantLockTest.java:23)
	at java.lang.Thread.run(Thread.java:748)
Locked:secondThread
UnLocked:secondThread
break before

分析:firstThread执行,secondThread不停的判断是否可以获得锁,当firstThread执行完,secondThread执行后被打断

例子2

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

public class ReentrantLockTest {
    ReentrantLock lock;

    ReentrantLockTest(ReentrantLock lock) {
        this.lock = lock;
    }

    private Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        if (lock.tryLock(700, TimeUnit.MILLISECONDS)) {
                            try {
                                System.out.println("Locked:" + Thread.currentThread().getName());
                                Thread.sleep(800);
                            } finally {
                                lock.unlock();
                                System.out.println("UnLocked:" + Thread.currentThread().getName());
                            }
                            System.out.println("break before");
                            break;
                        } else {
                            //System.out.println("Unable to lock " + Thread.currentThread().getName());
                        }

                    } catch (InterruptedException e){
                        System.out.println(Thread.currentThread() + " is Interupted");
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        ReentrantLockTest test = new ReentrantLockTest(lock);
        ReentrantLockTest test2 = new ReentrantLockTest(lock);
        Thread thread1 = new Thread(test.getRunnable(), "firstThread");
        Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

        thread1.start();
        thread2.start();
        try {
            Thread.sleep(300);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("interupt begin");
        thread2.interrupt();
        System.out.println("interupt end");
    }
}

一次执行结果

Locked:firstThread
interupt begin
interupt end
Thread[secondThread,5,main] is Interupted
java.lang.InterruptedException
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireNanos(AbstractQueuedSynchronizer.java:936)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireNanos(AbstractQueuedSynchronizer.java:1247)
	at java.util.concurrent.locks.ReentrantLock.tryLock(ReentrantLock.java:442)
	at com.jihite.templet.JavaBase.ReentrantLockTest$1.run(ReentrantLockTest.java:19)
	at java.lang.Thread.run(Thread.java:748)
Locked:secondThread
UnLocked:firstThread
break before
UnLocked:secondThread
break before

分析:firstThread执行,secondThread等待,等待过程被打断。打断后firstThread执行结束了,secondThread得到锁,继续执行

例子3

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest2 {
    ReentrantLock lock;

    ReentrantLockTest2(ReentrantLock lock) {
        this.lock = lock;
    }

    private Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        try {
                            lock.lock();
//                            lock.lockInterruptibly();
                            System.out.println("Locked:" + Thread.currentThread().getName());
                            Thread.sleep(800);
                            break;
                        } finally {
                            lock.unlock();
                            System.out.println("UnLocked:" + Thread.currentThread().getName());
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        ReentrantLockTest2 test = new ReentrantLockTest2(lock);
        ReentrantLockTest2 test2 = new ReentrantLockTest2(lock);
        Thread thread1 = new Thread(test.getRunnable(), "firstThread");
        Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

        thread1.start();
        thread2.start();
        try {
            Thread.sleep(600);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("interupt begin");
        thread2.interrupt();
        System.out.println("interupt end");
    }
}

一次执行结果

Locked:firstThread
interupt begin
interupt end
UnLocked:firstThread
Locked:secondThread
UnLocked:secondThread
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.jihite.templet.JavaBase.ReentrantLockTest2$1.run(ReentrantLockTest2.java:22)
	at java.lang.Thread.run(Thread.java:748)
Locked:secondThread
UnLocked:secondThread

分析:firstThread先获得锁执行,secondThread在等待,此时中断并未打断等待。firstThread执行完,secondThread获取后被打断

例子4

public class ReentrantLockTest2 {
    ReentrantLock lock;

    ReentrantLockTest2(ReentrantLock lock) {
        this.lock = lock;
    }

    private Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        try {
//                            lock.lock();
                            lock.lockInterruptibly();
                            System.out.println("Locked:" + Thread.currentThread().getName());
                            Thread.sleep(800);
                            break;
                        } finally {
                            lock.unlock();
                            System.out.println("UnLocked:" + Thread.currentThread().getName());
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        ReentrantLockTest2 test = new ReentrantLockTest2(lock);
        ReentrantLockTest2 test2 = new ReentrantLockTest2(lock);
        Thread thread1 = new Thread(test.getRunnable(), "firstThread");
        Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

        thread1.start();
        thread2.start();
        try {
            Thread.sleep(600);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("interupt begin");
        thread2.interrupt();
        System.out.println("interupt end");
    }
}

一次执行结果

Locked:firstThread
interupt begin
interupt end
Exception in thread "secondThread" java.lang.IllegalMonitorStateException
	at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
	at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
	at com.jihite.templet.JavaBase.ReentrantLockTest2$1.run(ReentrantLockTest2.java:25)
	at java.lang.Thread.run(Thread.java:748)

分析:lock.lockInterruptibly();在执行过程中可以响应中断时间

转载于:https://www.cnblogs.com/kaituorensheng/p/10645276.html

相关文章:

  • C学习笔记-makefile
  • cocos2dx笔记1:概述
  • 易语言QQpost加好友源码
  • Ansible-----常用功能
  • 2019春第六周学习编辑总结
  • 【感悟】一次不太好的寻找bug的体验,RecyclerView
  • mysql 命令启动
  • [题解]区间dp_luogu_P3147 262144
  • Permission denied: .gvfs
  • day2
  • JSP语法入门
  • 学习备忘英语单词转载
  • 存储的一些基本概念(HBA,LUN)
  • Kubenetes---Service--实践
  • HDU - 4352 XHXJ's LIS (数位dp)
  • hexo+github搭建个人博客
  • JS 中的深拷贝与浅拷贝
  • Codepen 每日精选(2018-3-25)
  • E-HPC支持多队列管理和自动伸缩
  • Java 实战开发之spring、logback配置及chrome开发神器(六)
  • ReactNative开发常用的三方模块
  • seaborn 安装成功 + ImportError: DLL load failed: 找不到指定的模块 问题解决
  • SpingCloudBus整合RabbitMQ
  • 创建一个Struts2项目maven 方式
  • 分享自己折腾多时的一套 vue 组件 --we-vue
  • 基于MaxCompute打造轻盈的人人车移动端数据平台
  • 将 Measurements 和 Units 应用到物理学
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • ​Z时代时尚SUV新宠:起亚赛图斯值不值得年轻人买?
  • ​云纳万物 · 数皆有言|2021 七牛云战略发布会启幕,邀您赴约
  • #define MODIFY_REG(REG, CLEARMASK, SETMASK)
  • (2021|NIPS,扩散,无条件分数估计,条件分数估计)无分类器引导扩散
  • (C语言)逆序输出字符串
  • (Java数据结构)ArrayList
  • (Redis使用系列) Springboot 整合Redisson 实现分布式锁 七
  • (二)换源+apt-get基础配置+搜狗拼音
  • (附源码)springboot课程在线考试系统 毕业设计 655127
  • (附源码)基于ssm的模具配件账单管理系统 毕业设计 081848
  • (接口封装)
  • (论文阅读11/100)Fast R-CNN
  • (全部习题答案)研究生英语读写教程基础级教师用书PDF|| 研究生英语读写教程提高级教师用书PDF
  • (四)Linux Shell编程——输入输出重定向
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • .htaccess配置常用技巧
  • .NET多线程执行函数
  • [1] 平面(Plane)图形的生成算法
  • [2019/05/17]解决springboot测试List接口时JSON传参异常
  • [AIGC] Nacos:一个简单 yet powerful 的配置中心和服务注册中心
  • [Android]Tool-Systrace
  • [Android]通过PhoneLookup读取所有电话号码
  • [C++]C++入门--引用
  • [CVPR2021]Birds of a Feather: Capturing Avian Shape Models from Images
  • [EFI]Acer Aspire A515-54g电脑 Hackintosh 黑苹果efi引导文件
  • [hdu 2896] 病毒侵袭 [ac自动机][病毒特征码匹配]
  • [IE9] IE9 RC版下载链接