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. uvm设计分析——report

    uvm_report实现中的类图,如下: 1)uvm_component均从uvm_report_object extend而来,其中定义了report_warning,error,info,fata ...

  2. python 爬取qidian某一页全部小说

      本文纯粹用于技术练习,请勿用作非法途径 import re import urllib.request from bs4 import BeautifulSoup import time url= ...

  3. Yii Restful api认证

  4. html5-label标签

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

  5. python读取excel中单元格的内容返回的5种类型

    (1) 读取单个sheetname的内容. 此部分转自:https://www.cnblogs.com/xxiong1031/p/7069006.html python读取excel中单元格的内容返回 ...

  6. Java多线程-----单例模式在多线程中的使用用问题

       1.饿汉模式(立即加载模式)与多线程 不管需不需要用到实例都要去创建实例,即在类产生的时候就创建好实例 package com.thread; /** * 饿汉模式 * * @author yy ...

  7. 普通程序员转型AI免费教程整合,零基础也可自学

    普通程序员转型AI免费教程整合,零基础也可自学 本文告诉通过什么样的顺序进行学习以及在哪儿可以找到他们.可以通过自学的方式掌握机器学习科学家的基础技能,并在论文.工作甚至日常生活中快速应用. 可以先看 ...

  8. Django MTV simple_tag filter inclusion_tag

    Django框架 模型(Model).视图(View)和控制器(Controller),具有耦合性低.重用性高.生命周期成本低等优点. MVC 框架 --  Model -View -Controll ...

  9. HDU 3172 Virtual Friends (map+并查集)

    These days, you can do all sorts of things online. For example, you can use various websites to make ...

  10. Eloquent JavaScript #07# Project: A Robot

    索引 Notes Excercise Measuring a robot Robot efficiency Persistent group 注释即笔记: const roads = [ " ...