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 ...
随机推荐
- 运行java程序的时候出现Exception in thread "main" java.lang.UnsupportedClassVersionError:
1 Exception in thread "main" java.lang.UnsupportedClassVersionError: com/test/inherited/In ...
- JAVA字符编码三:Java应用中的编码问题
第三篇:JAVA字符编码系列三:Java应用中的编码问题 这部分采用重用机制,引用一篇文章来完整本部分目标. 来源: Eceel东西在线 问题研究--字符集编码 地址:http://china.e ...
- vue+elementui项目打包后样式变化问题
博主刚刚解决了index.html空白问题,刚打开项目页面又发现了样式出现了大问题,样式与开发版本有很大不同,有些样式没有生效.利用搜索引擎,找到了问题所在以及解决办法:main.js中的引入顺序决定 ...
- [Web] HTML5新特性history pushState/replaceState解决浏览器刷新缓存
转载: https://www.jianshu.com/p/cf63a1fabc86 现实开发中,例如‘商品列表页’跳转‘商品详情页’,返回时,不重新加载刷新页面,并且滚动到原来的位置. 1.首先,先 ...
- Mysql 查询一个月当前时间一个月之前的数据
sql: AND date_format(createDTM, MONTH),'%Y-%m-%d')
- aardio类的例子
论坛里面相关资料太少,这里贴一下 库需要在工程的lib目录下,在ide里面就是用户库目录,比如 my_lib namespace my_lib{ import console class MyLibC ...
- django文章对本项目有用的收集
1.在django中使用自定义标签实现分页功能 https://www.cnblogs.com/MnCu8261/p/5943609.html https://www.cnblogs.com/bail ...
- 查看apache httpd server中加载了哪些模块
说明: 有的时候,需要查看当前apache中都加载了哪些模块,通过以下命令进行查看 [root@hadoop1 httpd-]# bin/apachectl -t -D DUMP_MODULES Lo ...
- [转]TrueType字体结构
TrueType字体通常包含在单个TrueType字体文件中,其文件后缀为.TTF. OpenType字体是以类似于TrueType字体的格式编码的POSTSCRIPT字体.OPENTYPE字体使用. ...
- html2canvas 将网页截图为图片,上传base64 到服务端
await html2canvas(getById("winyh"), { height:500, allowTaint: true, useCORS: true, }).then ...