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. WebStorage (1) 实例

    实例代码 <p>本页面每5秒刷新一下,这是您第<mark></mark>次进入本页面!</p> <script> if (window.lo ...

  2. html5-button元素

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  3. Visible Lattice Points (莫比乌斯反演)

    Visible Lattice Points 题意 : 从(0,0,0)出发在(N,N,N)范围内有多少条不从重合的直线:我们只要求gcd(x,y,z) = 1; 的点有多少个就可以了: 比如 : 点 ...

  4. CSS尺寸与补白属性-----margin和padding

       margin margin:[ <length> | <percentage> | auto ]{1,4}  为元素设置所有四个方向(上右下左)的外边距 auto:水平( ...

  5. MQ(转)

    1. 到底什么时候该使用MQ? 1). 典型场景一:数据驱动的任务依赖 采用MQ的优点是: a. 不需要预留buffer,上游任务执行完,下游任务总会在第一时间被执行 b. 依赖多个任务,被多个任务依 ...

  6. 转:异常处理之ThreadException、unhandledException及多线程异常处理

    转载自:http://www.cnblogs.com/levin9/articles/2319251.html 一:ThreadException和unhandledException的区别 处理未捕 ...

  7. Radio中REG

    Auto REG/REG OFF在广播接收质量不好时,收音机首先仅调整到该广播电台当前发射的可选频率.但是,如果接收质量差到“该发射电台濒临消失”的程度,则收音机也会接收德国NDR1(北德意志广播电台 ...

  8. 大数据学习路线:Zookeeper集群管理与选举

    大数据技术的学习,逐渐成为很多程序员的必修课,因为趋势也是因为自己的职业生涯.在各个技术社区分享交流成为很多人学习的方式,今天很荣幸给我们分享一些大数据基础知识,大家可以一起学习! 1.集群机器监控 ...

  9. 清明 DAY2

    数论 数论是研究整数性质的东西 也就是 lim   π(x)=x/ ln x (x->无穷) 证明: ∵ p|ab ∴ ab有因子p 设 a=p1k1p2k2......prkr      b= ...

  10. logger日志模块

    简单配合模式: import logging#简单配置logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s ...