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. 二 js表达式与运算符

    /** * Created by Administrator on 2017/12/14. * 表达式与运算符 */ //1.基本表达式 加减乘除 var a = 4; a = 7/6; var b ...

  2. 四则运算 python

    2018103004四则运算练习软件项目报告   此作业的要求参见链接的任务三个人任务:https://mooc1-1.chaoxing.com/mycourse/studentstudy?chapt ...

  3. 了解一下UTF-16

    1)先啰嗦一下 UTF-16是一种编码格式.啥是编码格式?就是怎么存储,也就是存储的方式. 存储啥?存二进制数字.为啥要存二进制数字? 因为Unicode字符集里面把二进制数字和字符一一对应了,存二进 ...

  4. 20165305 苏振龙《Java程序设计》第四周课上测试补做

    第一次测试 第二次测试 第三次测试 上传代码 第四次测试 总结 之前我一直在git bash进行程序设计,但是对于我来说操作起来有点困难,所以我改用了虚拟机,之后之前一直困扰我的问题在虚拟机下就没有了 ...

  5. elsearch

    1. ElasticSearch是性能优化的分布式全文搜索引擎,存储数据的载体是文档(Document),它的优势在于搜索速度快和支持聚合操作,在更新文档时,基本上能够达到实时搜索.ElasticSe ...

  6. PIVOT(透视转换)和UNPIVOT(逆透视转换)

    一.原数据状态 二.手动写透视转换1 三.手动写透视转换2 四.PIVOT(透视转换)和UNPIVOT(逆透视转换)详细使用 使用标准SQL进行透视转换和逆视转换 --行列转换 create tabl ...

  7. 转:C# 对委托的BeginInvoke,EndInvoke 及Control 的BeginInvoke,EndInvoke 的理解

    转载自:http://www.cnblogs.com/easyfrog/p/3141269.html using System; using System.Collections.Generic; u ...

  8. RN与android原生开发混合后的环境报错问题

    RN与android原生开发混合后的环境报错问题 需要先安装nodejs$ yarn --version1.12.1更新当前版本yarn upgrade --latest安装 | Yarnhttps: ...

  9. hashCode 一致性hash 算法

    1 如果两个对象相同,那么它们的hashCode值一定要相同.也告诉我们重写equals方法,一定要重写 hashCode方法,同一个对象那么hashcode就是同一个(同一个对象什么都是相同的).2 ...

  10. [转载]Javascript:history.go()和history.back()的用法和区别

    Javascript:history.go()和history.back()的用法和区别 简单的说就是:go(-1): 返回上一页,原页面表单中的内容会丢失:back(): 返回上一页,原页表表单中的 ...