Java并发之ReentrantLock
来源:互联网 发布:openwrt防网络尖兵 编辑:程序博客网 时间:2024/05/08 00:55
package com.lxht.test;import com.lxht.emos.system.seqs.service.SystemSeqsService;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class TestReenTrantLock { public static void main(String[] args) { ReentrantLock reentLock = new ReentrantLock(); //创建ReentrantLock
/**
* 创建一个Condition;
* Condition可以实现原来Object的wait(),和notify(),notifyAll()功能,但为什么要新增一个condition呢?
* Condition比原来Object.wait()和Object.notify()功能更灵活,一个ReentrantLock可以创建多个Condition,这样不同的线程可以使用不同的Condition.awit(),
* 这样可以灵活的实现部分线程的唤醒,而不用唤醒全部的线程;
*/
Condition condition = reentLock.newCondition();
ReentrantThread thread1 = new ReentrantThread(reentLock,condition);
ReentrantThread thread2 = new ReentrantThread(reentLock,condition);
ReentrantThread thread3 = new ReentrantThread(reentLock,condition);
thread1.start();
thread2.start();
thread3.start();
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
try {
reentLock.lock(); //加锁,注意:多次调用lock()后需要调用配对的unlock()方法解锁, 如果当前Thread调用了2次lock(),则必须执行2次unlock()
System.out.println("singall all is running....");
condition.signalAll(); //唤醒condition上所有等待的Thread
} catch (Exception e) {
e.printStackTrace();
} finally {
reentLock.unlock(); //释放锁
}
}
}
class ReentrantThread extends Thread{
private ReentrantLock reentrantLock;
private Condition condition;
public ReentrantThread(ReentrantLock reentrantLock,Condition condition) {
this.reentrantLock = reentrantLock;
this.condition = condition;
}
public void run() {
int[] cc = new int[]{0,1,2}; try{
reentrantLock.lock();
for (int i : cc) {
System.out.println(this.getName() + ":" + i);
}
condition.await(); //当前Thread进入等待状态,这时会释放lock;
System.out.println("awiat is end....." + this.getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
System.out.println("unlock," + this.getName());
}
}
}
阅读全文
0 0
- java并发之ReentrantLock
- Java并发之ReentrantLock
- Java并发之ReentrantLock详解
- Java并发之ReentrantLock详解
- JAVA并发编程学习笔记之ReentrantLock
- JAVA并发编程学习笔记之ReentrantLock
- 【Java之并发】ReentrantLock和synchronized区别
- java 并发编程学习之三 ---- ReentrantLock
- Java并发编程之ReentrantLock源码解析
- 【Java并发】- ReentrantLock,重入锁
- Java并发包--ReentrantLock
- java并发中的ReentrantLock
- 【Java】深入Java多线程和并发编程之ReentrantLock
- Java 并发编程之ReentrantLock和synchronized锁
- JAVA并发编程学习笔记之ReentrantLock (r)
- 【死磕Java并发】-----J.U.C之重入锁:ReentrantLock
- 实战Java高并发程序设计之ReentrantLock(一)
- 实战Java高并发程序设计之ReentrantLock(二)
- nginx的yum 和 源码包 安装的 区别
- linux下的C语言开发(makefile编写)
- 上一个排列算法java
- java流概述
- 向centos中拖放文件
- Java并发之ReentrantLock
- Http GET的传输方式
- AndroidStudio 中5.0以下的模拟器无法联网的问题 记录
- Lua学习笔记之table
- String相关
- 为电脑加装固态硬盘
- 初见Java多线程(二、线程的创建与启动)
- 我的前端入门之html标签
- Mybatis中foreach循环