JAVA-AbstractQueuedSynchronizer-AQS
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; @Slf4j
public class CountDownLatchExample1 {
private final static int threadCount=200;
public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newCachedThreadPool();
final CountDownLatch countDownLatch=new CountDownLatch(threadCount);
for(int i=0;i<threadCount;i++){
final int threadNum=i;
executorService.execute(()->{
try{
test(threadNum);
}catch (Exception e){
log.error("exception",e);
}finally {
countDownLatch.countDown();
}
});
}
//countDownLatch.await(); //保证前面的线程都执行完
countDownLatch.await(10, TimeUnit.MILLISECONDS); //在规定时间内执行
log.info("finish");
}
private static void test(int threadNum) throws Exception{
Thread.sleep(100);
log.info("{}",threadNum);
Thread.sleep(100);
}
}
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore; @Slf4j
public class SemaphoreExample1 {
private final static int threadCount=20;
public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newCachedThreadPool();
final Semaphore semaphore=new Semaphore(3);
for(int i=0;i<threadCount;i++){
final int threadNum=i;
executorService.execute(()->{
try{
if(semaphore.tryAcquire()){ //可以指定执行的时间
test(threadNum);
semaphore.release();
}
//semaphore.acquire(3);//获取多个许可
//semaphore.acquire();//获取一个许可
// test(threadNum);
// semaphore.release();//释放一个许可
//semaphore.release(3);//释放多个许可
}catch (Exception e){
log.error("exception",e);
}
});
} log.info("finish");
}
private static void test(int threadNum) throws Exception{
log.info("{}",threadNum);
Thread.sleep(100);
}
}
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*; @Slf4j
public class CyclicBarrierExamle1 {
//private static CyclicBarrier barrier=new CyclicBarrier(5);
private static CyclicBarrier barrier=new CyclicBarrier(5,()->{
log.info("callback is running");
});
public static void main(String[] args) throws Exception{
ExecutorService executor= Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
final int threadNum=i;
Thread.sleep(1000);
executor.execute(()->{
try {
race(threadNum);
}catch (Exception e){
log.error("exception",e);
}
});
}
executor.shutdown();
}
private static void race(int threadNum) throws Exception{
Thread.sleep(100);
log.info("{} is ready",threadNum);
//barrier.await();
try {
barrier.await(2000, TimeUnit.MILLISECONDS);
}catch (BrokenBarrierException |TimeoutException e){
log.warn("BrokenBarrierException",e);
} log.info("{}continue",threadNum);
}
}
在读取中写入的方法:ReentrantReadWriteLock
线程安全的写法。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; @Slf4j
public class LockExample1 {
//请求总数
public static int clientTotal=5000;
//同时并发执行的线程数
public static int threadTotal=200;
public static int count=0;
private final static Lock lock=new ReentrantLock(); public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newCachedThreadPool();
final Semaphore semaphore=new Semaphore(threadTotal);
final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
for(int i=0;i<clientTotal;i++){
final int count=i;
executorService.execute(()->{
try {
semaphore.acquire();
add(count);
semaphore.release();
}catch (Exception e){
log.error("exception",e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("size{}",count);
}
private static void add(int i){
lock.lock();
try {
count++;
}finally {
lock.unlock();
}
}
}
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock; @Slf4j
public class LockExample2 {
private final Map<String, Data> map=new TreeMap<>();
private final ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
private final Lock readLock=lock.readLock();
private final Lock writeLock=lock.writeLock();
public Data get(String key){
readLock.lock();
try {
return map.get(key);
}finally {
readLock.unlock();
}
}
public Set<String> getAllKeys(){
readLock.lock();
try {
return map.keySet();
}finally {
readLock.unlock();
}
}
public Data put(String key, Data value){
writeLock.lock();
try {
return map.put(key, value);
}finally {
readLock.unlock();
}
}
class Data{ }
}
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.StampedLock; @Slf4j
public class LockExample5 {
//请求总数
public static int clientTotal=5000;
//同时并发执行的线程数
public static int threadTotal=200;
public static int count=0;
private final static StampedLock lock=new StampedLock(); public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newCachedThreadPool();
final Semaphore semaphore=new Semaphore(threadTotal);
final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
for(int i=0;i<clientTotal;i++){
final int count=i;
executorService.execute(()->{
try {
semaphore.acquire();
add(count);
semaphore.release();
}catch (Exception e){
log.error("exception",e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("size{}",count);
}
private static void add(int i){
long stamp= lock.writeLock();
try {
count++;
}finally {
lock.unlock(stamp);
}
}
}
import java.util.concurrent.locks.StampedLock;
public class LockExample4 {
class Point{
private double x,y;
private final StampedLock sl=new StampedLock();
void move(double deltaX,double deltaY){
long stamp=sl.writeLock();
try{
x+=deltaX;
y+=deltaY;
}finally {
sl.unlockWrite(stamp);
}
} //乐观锁案例
double distanceFromOrigin(){
long stamp=sl.tryOptimisticRead();//获得一个乐观读锁
double currentX=x,currentY=y;//将两个字段读入本地局部变量
if(!sl.validate(stamp)){ //检查发出乐观锁后同时是否有其他锁发生
stamp=sl.readLock();//没有,再次获取一个读悲观锁
try{
currentX=x; //将两个字段读入本地局部变量
currentY=y; //将两个字段读入本地局部变量
}finally {
sl.unlockRead(stamp);
}
}
return Math.sqrt(currentX*currentX+currentY*currentY);
} //悲观锁读写案例
void moveIfAtOrigin(double newX,double newY){
long stamp=sl.readLock();
try {
while (x==0.0&&y==0.0){ //循环,检查当前状态是否符合
long ws=sl.tryConvertToWriteLock(stamp);//将读锁转化为写锁
if(ws!=0L){ //确认转为写锁是否成功
stamp=ws; //如果成功,替换票据
x=newX; //进行状态改变
y=newY; //进行状态改变
break;
}else {
sl.unlockRead(stamp);//如果不能成功转化为写锁
stamp=sl.writeLock();//显示直接进行写锁,然后通过循环再试
}
}
}finally {
sl.unlock(stamp);//释放读锁和写锁
}
}
}
}
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class LockExample6 {
public static void main(String[] args) {
ReentrantLock reentrantLock=new ReentrantLock();
Condition condition=reentrantLock.newCondition();
new Thread(()->{
try {
reentrantLock.lock();
log.info("wait signal");
condition.await();
}catch (InterruptedException e){
e.printStackTrace();
}
log.info("get signal");
reentrantLock.unlock();
}).start(); new Thread(()->{
reentrantLock.lock();
log.info("get lock");
try {
Thread.sleep(300);
}catch (InterruptedException e){
e.printStackTrace();
}
condition.signalAll();
log.info("send signal~");
reentrantLock.unlock();
}).start();
}
}
JAVA-AbstractQueuedSynchronizer-AQS的更多相关文章
- 4.从AbstractQueuedSynchronizer(AQS)说起(3)——AQS结语
前两节的内容<2.从AbstractQueuedSynchronizer(AQS)说起(1)——独占模式的锁获取与释放> .<3.从AbstractQueuedSynchronize ...
- 9.深入理解AbstractQueuedSynchronizer(AQS)
1. AQS简介 在上一篇文章中我们对lock和AbstractQueuedSynchronizer(AQS)有了初步的认识.在同步组件的实现中,AQS是核心部分,同步组件的实现者通过使用AQS提供的 ...
- [Java并发] AQS抽象队列同步器源码解析--锁获取过程
要深入了解java并发知识,AbstractQueuedSynchronizer(AQS)是必须要拿出来深入学习的,AQS可以说是贯穿了整个JUC并发包,例如ReentrantLock,CountDo ...
- 深入理解AbstractQueuedSynchronizer(AQS)
本人免费整理了Java高级资料,涵盖了Java.Redis.MongoDB.MySQL.Zookeeper.Spring Cloud.Dubbo高并发分布式等教程,一共30G,需要自己领取.传送门:h ...
- Java:AQS 小记-2(ReentrantLock)
Java:AQS 小记-2(ReentrantLock) 整体结构 ReentrantLock 类图 AbstractOwnableSynchronizer 类 public abstract cla ...
- Java:AQS 小记-1(概述)
Java:AQS 小记-1(概述) 概述 全称是 Abstract Queued Synchronizer(抽象队列同步器),是阻塞式锁和相关的同步器工具的框架,这个类在 java.util.conc ...
- [Java并发] AQS抽象队列同步器源码解析--独占锁释放过程
[Java并发] AQS抽象队列同步器源码解析--独占锁获取过程 上一篇已经讲解了AQS独占锁的获取过程,接下来就是对AQS独占锁的释放过程进行详细的分析说明,废话不多说,直接进入正文... 锁释放入 ...
- 同步类的基础AbstractQueuedSynchronizer(AQS)
同步类的基础AbstractQueuedSynchronizer(AQS) 我们之前介绍了很多同步类,比如ReentrantLock,Semaphore, CountDownLatch, Reentr ...
- 全网最详细的AbstractQueuedSynchronizer(AQS)源码剖析(二)资源的获取和释放
上期的<全网最详细的AbstractQueuedSynchronizer(AQS)源码剖析(一)AQS基础>中介绍了什么是AQS,以及AQS的基本结构.有了这些概念做铺垫之后,我们就可以正 ...
- Java并发框架AbstractQueuedSynchronizer(AQS)
1.前言 本文介绍一下Java并发框架AQS,这是大神Doug Lea在JDK5的时候设计的一个抽象类,主要用于并发方面,功能强大.在新增的并发包中,很多工具类都能看到这个的影子,比如:CountDo ...
随机推荐
- Pytest权威教程19-编写钩子(Hooks)方法函数
目录 编写钩子(Hooks)函数 钩子函数验证和执行 firstresult: 遇到第一个有效(非None)结果返回 hookwrapper:在其他钩子函数周围执行 钩子(Hooks)函数排序/调用示 ...
- python requests 保存图片
html = requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec ...
- Fluent设置充分发展湍流入口(利用profile)
计算模型: 物性参数为: 密度:100kg/m3 粘度系数:0.003333kg/(m·s) 原视频下载地址: https://pan.baidu.com/s/1W3n_K-dZCVMF7M63wV2 ...
- [原创]App弱网测试方法介绍
[原创]App弱网测试方法介绍 1 什么是弱网? 弱网就是在非正常网络状态下,用户在访问网络时遭遇到网络延迟或是丢包,造成使用产品时用户体验不佳或反感的场景. 2 为什么要进行弱网测试 简而方之, ...
- python操作mysql基础一
python操作mysql基础一 使用Python操作MySQL的一些基本方法 前奏 为了能操作数据库, 首先我们要有一个数据库, 所以要首先安装Mysql, 然后创建一个测试数据库python_te ...
- Chrome提示:"请停用以开发者模式运行的扩展程序"的解决办法
操作步骤 1.开始 -> 运行 -> 输入gpedit.msc -> 回车确定打开计算机本地组策略编辑器(通过Win + R快捷键可以快速打开运行),如图所示: 2.在打开的本地组策 ...
- LiteIDE 设置默认编译输出位置
go build命令默认输出路径是当前工作路径,这个显得比较乱,我习惯于把输出文件放置在项目的build目录下,这样方便查找,已经同步备份的时候排除不必要的文件. go build命令可以指定-o 输 ...
- windows server core 2016 IIS远程管理的那些坑
打算从win10访问数据中心版2016 core,结果IIS远程管理不了. 需要修改core上防火墙和注册表,开启一些相关服务. 具体需要如下操作. 1.win10 启用IIS管理特性 2.参考htt ...
- Xamarin.Forms Shell基础教程(1)
Xamarin.Forms Shell基础教程(1) 什么是Xamarin.Forms Shell Shell是Visual Studio为Xamarin Forms提供的解决方案模版.本质上,She ...
- [原]JSON 字符串(值)做判断,比较 “string ”
现在我这样一个json字符串: char* cjson = "{\"code\": \"200\", \"code2\": 200 ...