Lock接口

package concurency.chapter9;

import java.util.Collection;

public interface Lock {
static class TimeOutException extends Exception {
TimeOutException(String message) {
super(message);
}
} void lock() throws InterruptedException; void lock(long mills) throws InterruptedException,TimeOutException; void unlock(); Collection<Thread> getBlockedThread(); int getBlockedSize();
}

Lock实现类

package concurency.chapter9;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional; public class BooleanLock implements Lock{
public BooleanLock(boolean initValue) {
this.initValue = initValue;
} // false means is free
// true means having been used
private boolean initValue; private Thread currentThread; private Collection<Thread> blockedThreads = new ArrayList<>(); @Override
public synchronized void lock() throws InterruptedException {
while(initValue) {
blockedThreads.add(Thread.currentThread());
this.wait();
} blockedThreads.remove(Thread.currentThread());
this.initValue = true;
this.currentThread = Thread.currentThread();
} @Override
public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
// less than 0, Ignore it..
if(mills <= 0)
lock();
long hasRemaining = mills;
long endTime = System.currentTimeMillis() + mills;
while(initValue) {
if(hasRemaining <= 0)
throw new TimeOutException("time out, and the Thread[" + Thread.currentThread().getName()+"] do not get the lock");
blockedThreads.add(Thread.currentThread());
this.wait(mills);
hasRemaining = endTime - System.currentTimeMillis();
}
blockedThreads.remove(Thread.currentThread());
this.initValue = true;
this.currentThread = Thread.currentThread();
} @Override
public synchronized void unlock() {
if(currentThread != null && Thread.currentThread() == currentThread) {
this.initValue = false;
Optional.of(Thread.currentThread().getName() + " release the lock...").ifPresent(System.out::println);
this.notifyAll();
}
} @Override
public Collection<Thread> getBlockedThread() {
return Collections.unmodifiableCollection(blockedThreads);
} @Override
public int getBlockedSize() {
return blockedThreads.size();
}
}

测试

package concurency.chapter9;

import java.util.Optional;
import java.util.stream.Stream; public class LockTest {
public static void main(String[] args) throws InterruptedException { final BooleanLock booleanLock = new BooleanLock(false);
Stream.of("T1", "T2", "T3", "T4")
.forEach(name ->
new Thread(() -> {
try {
booleanLock.lock(1000L);
Optional.of(Thread.currentThread().getName() + " have the lock Monitor")
.ifPresent(System.out::println);
work();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Lock.TimeOutException e) {
System.out.println(e.getMessage());
// Optional.of(Thread.currentThread().getName() + " time out")
// .ifPresent(System.out::println);
} finally {
booleanLock.unlock();
}
}, name).start()
);
} private static void work() throws InterruptedException {
Optional.of(Thread.currentThread().getName() + " is Working...")
.ifPresent(System.out::println);
Thread.sleep(10_000);
}
}

测试结果

T1 have the lock Monitor
T1 is Working...
time out, and the Thread[T2] do not get the lock
time out, and the Thread[T3] do not get the lock
time out, and the Thread[T4] do not get the lock
T1 release the lock...

Java 实现一个自己的显式锁Lock(有超时功能)的更多相关文章

  1. java线程基础巩固---如何实现一个自己的显式锁Lock

    拋出synchronized问题: 对于一个方法上了同锁如果被一个线程占有了,而假如该线程长时间工作,那其它线程不就只能傻傻的等着,而且是无限的等这线程工作完成了才能执行自己的任务,这里来演示一下这种 ...

  2. Java编程的逻辑 (71) - 显式锁

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  3. Java并发编程系列-(4) 显式锁与AQS

    4 显示锁和AQS 4.1 Lock接口 核心方法 Java在java.util.concurrent.locks包中提供了一系列的显示锁类,其中最基础的就是Lock接口,该接口提供了几个常见的锁相关 ...

  4. “全栈2019”Java多线程第三十二章:显式锁Lock等待唤醒机制详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  5. 4.显式锁 Lock

    4.1 概念 内置锁 vs 显示锁 synchronize是java语言层面实现的锁,称为内置锁.使用方便代码简洁,而且在jdk新版本优化后,性能也得到了很大的提高.synchronize是一个可重入 ...

  6. java并发多线程显式锁Condition条件简介分析与监视器 多线程下篇(四)

    Lock接口提供了方法Condition newCondition();用于获取对应锁的条件,可以在这个条件对象上调用监视器方法 可以理解为,原本借助于synchronized关键字以及锁对象,配备了 ...

  7. java 并发多线程显式锁概念简介 什么是显式锁 多线程下篇(一)

    目前对于同步,仅仅介绍了一个关键字synchronized,可以用于保证线程同步的原子性.可见性.有序性 对于synchronized关键字,对于静态方法默认是以该类的class对象作为锁,对于实例方 ...

  8. java之AQS和显式锁

    本次内容主要介绍AQS.AQS的设计及使用.ReentrantLock.ReentrantReadWriteLock以及手写一个可重入独占锁 1.什么是AQS? AQS,队列同步器AbstractQu ...

  9. Java并发-显式锁篇【可重入锁+读写锁】

    作者:汤圆 个人博客:javalover.cc 前言 在前面并发的开篇,我们介绍过内置锁synchronized: 这节我们再介绍下显式锁Lock 显式锁包括:可重入锁ReentrantLock.读写 ...

随机推荐

  1. Mvcpager以下各节已定义,但尚未为布局页“~/Views/Shared/_Layout.cshtml”呈现:“Scripts”。

    解决办法如下: 1.在_Layout.cshtml布局body内,添加section,Scripts.Render和RenderSection标签示例代码如下: <body class=&quo ...

  2. word自动编号后面空格位置太大了

    选择你需要调整的段落.右键点击.选择“调整列表缩进” 然后在弹出的窗口中,第三行的“制表符”改成“空格”即可.或者空格都不需要可以改为“不特别标注”

  3. Robot Framework 教程 (3) - Resource及关键字 的使用

    From:http://www.cnblogs.com/buaawp/p/4754399.html Robot Framework 教程 (3) - Resource及关键字 的使用 在进行软件自动化 ...

  4. 排序(Sort)-----冒泡排序

    声明:文中动画转载自https://blog.csdn.net/qq_34374664/article/details/79545940    1.冒泡排序简介 冒泡排序(Bubble Sort),又 ...

  5. SVN && BeyondCompare

    [1]设置内容 (1)三个步骤对应设置内容 1.1 "D:\Beyond Compare 4\BCompare.exe" %base %mine /title1=%bname /t ...

  6. linux常用命令:cd 命令

    Linux cd 命令可以说是Linux中最基本的命令语句,其他的命令语句要进行操作,都是建立在使用 cd 命令上的.所以,学习Linux 常用命令,首先就要学好 cd 命令的使用方法技巧. 1. 命 ...

  7. Redis性能监控

    参考地址: redis教程:http://www.runoob.com/redis/redis-tutorial.html redis百度百科:https://baike.baidu.com/item ...

  8. SQL Server双机热备之后项目的FailOver自动连接

    SQL Server配置数据库镜像后,可能有朋友们会比较有疑惑,你一下搞两个数据库出来,他们的ip地址都不一样,到时候数据库切换过去了,我的数据库的连接字符串可如何是好?难道还得在代码中去控制是连接哪 ...

  9. 关于mapreducer 读取hbase数据 存入mysql的实现过程

    mapreducer编程模型是一种八股文的代码逻辑,就以用户行为分析求流存率的作为例子 1.map端来说:必须继承hadoop规定好的mapper类:在读取hbase数据时,已经有现成的接口 Tabl ...

  10. solr 使用指定数据源

    1,将solr 解压,我们观察发现它其实即可以是web服务也可以做数据分析 数据库 2,我们在example目录下新建一个hai的文件夹,用于存放数据 参考solr 目录,将solr.xml 复制一份 ...