技术标签: 高并发与线程安全
countDownLatch初始化一个数值,阻塞线程知道倒数到0触发事件
class countDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i <=6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 上完自习,离开教室");
},String.valueOf(i)).start();
}
System.out.println(Thread.currentThread().getName()+"\t >>>>关门走人");
TimeUnit.SECONDS.sleep(2);
System.out.println("------------");
for (int i = 1; i <=6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 上完自习,离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
//阻止主线程,等待子线程完成
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"\t <<<<关门走人");
}
}
/*
1 上完自习,离开教室
2 上完自习,离开教室
main >>>>关门走人
3 上完自习,离开教室
4 上完自习,离开教室
0 上完自习,离开教室
5 上完自习,离开教室
6 上完自习,离开教室
------------
2 上完自习,离开教室
4 上完自习,离开教室
1 上完自习,离开教室
5 上完自习,离开教室
3 上完自习,离开教室
6 上完自习,离开教室
main <<<<关门走人
*/
cyclicBarrier向上计数,线程阻塞
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("召唤神龙");
});
for (int i = 1; i <=7; i++) {
final int tempint=i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t收集了第:"+tempint+"颗龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
/*
2 收集了第:2颗龙珠
6 收集了第:6颗龙珠
3 收集了第:3颗龙珠
1 收集了第:1颗龙珠
7 收集了第:7颗龙珠
4 收集了第:4颗龙珠
5 收集了第:5颗龙珠
召唤神龙
*/
semaphore信号量
public class SemaphoreDemo {
public static void main(String[] args) {
//初始化资源数
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"\t抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"\t我走了");
} catch (Exception e) {
e.printStackTrace();
}
finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
/*
2 抢到车位
1 抢到车位
3 抢到车位
2 我走了
3 我走了
1 我走了
6 抢到车位
4 抢到车位
5 抢到车位
6 我走了
5 我走了
4 我走了
*/
public enum CountryEnum {
ONE(1,"春"),TWO(2,"夏");
private Integer retId;
private String retMessage;
public Integer getRetId() {
return retId;
}
public String getRetMessage() {
return retMessage;
}
CountryEnum(Integer retId, String retMessage) {
this.retId = retId;
this.retMessage = retMessage;
}
public static CountryEnum getEnumForIndex(int index){
CountryEnum[] values = CountryEnum.values();
for (CountryEnum countryEnum: values) {
if (countryEnum.retId==index){
return countryEnum;
}
}
return null;
}
}
阻塞队列的好处?不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程。
阻塞队列如何管理?
何为阻塞队列?
阻塞队列分类
ArrayBlockingQueue:由数组结构组成的有限阻塞队列
LinkedBlockingQueue:由链表结构组成的有界阻塞队列(默认大小Integer.MAX_VALUE)
PriorityBlockingQueue:支持优先级排序的无界阻塞队列
DelayQueue:使用优先级队列实现的延迟无解阻塞队列
SynchronousQueue:不存储元素的阻塞队列,也即单个元素的队列
LinkedTransferQueue:由链表结构组成的无解阻塞队列
LinkedBlockingDeque:由链表结构组成的双向阻塞队列
阻塞队列的核心方法
抛出异常:当操作超过队列长度时,直接抛出异常
特殊值:进行尝试操作,如果成功返回true,失败返回false
阻塞:如果队列满了继续插入就阻塞线程,直到有元素移除;如果队列为空还要取出就阻塞线程
超时:只阻塞指定的超时时间
方法类型 | 抛出异常 | 特殊值 | 阻塞 | 超时 |
---|---|---|---|---|
插入 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
检查 | element() | peek() | 不可用 | 不可用 |
//抛出异常
public class BlockingQueueDemo {
public static void main(String[] args) {
arrayBlockingQueue_exception();
}
private static void arrayBlockingQueue_exception() {
//初始化一个大小为3的string阻塞队列
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.element());
try {
System.out.println(blockingQueue.add("a"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("--------------------");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.element());
try {
System.out.println(blockingQueue.remove());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
true
true
true
a
java.lang.IllegalStateException: Queue full
at java.util.AbstractQueue.add(AbstractQueue.java:98)
at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
at queue.BlockingQueueDemo.main(BlockingQueueDemo.java:24)
--------------------
a
b
c
Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractQueue.element(AbstractQueue.java:136)
at queue.BlockingQueueDemo.main(BlockingQueueDemo.java:33)
*/
//特殊值
public class BlockingQueueDemo {
public static void main(String[] args) {
arrayBlockingQueue_special();
}
private static void arrayBlockingQueue_special() {
//初始化一个大小为3的string阻塞队列
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println("队列已满尝试插入");
System.out.println(blockingQueue.offer("d"));
System.out.println("检查队列");
System.out.println(blockingQueue.peek());
System.out.println("移除元素");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println("队列已空");
System.out.println(blockingQueue.poll());
}
}
/*
true
true
true
队列已满尝试插入
false
检查队列
a
移除元素
a
b
c
队列已空
null
*/
//阻塞
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
arrayBlockingQueue_blocking();
}
private static void arrayBlockingQueue_blocking() throws InterruptedException {
//初始化一个大小为3的string阻塞队列
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
System.out.println("队列已满尝试插入,此时线程阻塞");
System.out.println(blockingQueue.peek());
blockingQueue.take();
blockingQueue.take();
blockingQueue.take();
System.out.println("队列已空,若继续清空线程阻塞");
}
}
//超时
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
timeOut();
}
private static void timeOut() throws InterruptedException {
//初始化一个大小为3的string阻塞队列
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
//s瞬间插入
System.out.println(blockingQueue.offer("a", 2l, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("b", 2l, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("c", 2l, TimeUnit.SECONDS));
System.out.println("队列已满,此时尝试插入,等待两秒返回插入结果");
System.out.println(blockingQueue.offer("d", 2l, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(1l, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(1l, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(1l, TimeUnit.SECONDS));
System.out.println("队列已空,此时尝试获取,等待一秒返回获取结果");
System.out.println(blockingQueue.poll(1l, TimeUnit.SECONDS));
}
}
/*
true
true
true
队列已满,此时尝试插入,等待两秒返回插入结果
false
a
b
c
队列已空,此时尝试获取,等待一秒返回获取结果
null
*/
队列中只有一个元素,不消费就不生产
public class SycnhronousQueueDemo {
public static void main(String[] args) {
SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"\t put 1");
synchronousQueue.put("1");
System.out.println(Thread.currentThread().getName()+"\t put 2");
synchronousQueue.put("2");
System.out.println(Thread.currentThread().getName()+"\t put 3");
synchronousQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"AA").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("2s后");
System.out.println(Thread.currentThread().getName()+"\tget "+synchronousQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println("2s后");
System.out.println(Thread.currentThread().getName()+"\tget "+synchronousQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println("2s后");
System.out.println(Thread.currentThread().getName()+"\tget "+synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"BB").start();
}
}
/*
AA put 1
2s后
BB get 1
AA put 2
2s后
BB get 2
AA put 3
2s后
BB get 3
*/
生产者消费者模式
传统版
class ShareData{
private int number=0;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void increment() throws Exception{
try {
lock.lock();
//1判断,防止虚假唤醒
while (number!=0){
//等待,暂停生产
condition.await();
}
//2干活
number++;
System.out.println(Thread.currentThread().getName()+"\t "+number);
//3通知唤醒
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void decrement() throws Exception{
try {
lock.lock();
//1判断
while (number==0){
//等待,暂停生产
condition.await();
}
//2干活
number--;
System.out.println(Thread.currentThread().getName()+"\t "+number);
//3通知唤醒
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class ProdConsumer_TranditionDemo {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(()->{
for (int i = 1; i <= 5; i++) {
try {
shareData.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(()->{
for (int i = 1; i <= 5; i++) {
try {
shareData.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
},"BB").start();
}
}
/*
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
*/
虚假唤醒
阻塞队列版
class MyResource{
private volatile boolean flag=true;
private AtomicInteger atomicInteger=new AtomicInteger();
//定义基础接口
BlockingQueue<String> blockingQueue=null;
//通过构造传入具体的实现类
public MyResource(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
public void myProd() throws InterruptedException {
String data=null;
boolean resValue;
while (flag){
data=atomicInteger.incrementAndGet()+"";
resValue=blockingQueue.offer(data,2l, TimeUnit.SECONDS);
if (resValue){
System.out.println(Thread.currentThread().getName()+"\t 插入队列成功"+data);
}else {
System.out.println(Thread.currentThread().getName()+"\t 插入队列失败" );
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println(Thread.currentThread().getName()+"\t 生产叫停");
}
public void myConsumer() throws InterruptedException {
String result=null;
while (flag){
//外部设置flag时线程处于阻塞状态
result=blockingQueue.poll(2l,TimeUnit.SECONDS);
if (result==null||result.equalsIgnoreCase("")){
flag=false;
System.out.println(Thread.currentThread().getName()+"\t 消费失败");
break;
}
System.out.println(Thread.currentThread().getName()+"\t 消费队列"+result+"成功");
}
}
public void stop(){
System.out.println("开始停止生产");
flag=false;
}
}
public class ProdConsumer_BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(5);
MyResource myResource = new MyResource(blockingQueue);
new Thread(()->{
System.out.println("生产线程启动");
System.out.println();
System.out.println();
try {
myResource.myProd();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"生产者").start();
new Thread(()->{
System.out.println("消费线程启动");
System.out.println();
System.out.println();
try {
myResource.myConsumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"消费者").start();
TimeUnit.SECONDS.sleep(3);
myResource.stop();
}
}
/*
java.util.concurrent.ArrayBlockingQueue
生产线程启动
消费线程启动
生产者 插入队列成功1
消费者 消费队列1成功
生产者 插入队列成功2
消费者 消费队列2成功
生产者 插入队列成功3
消费者 消费队列3成功
开始停止生产
生产者 生产叫停
消费者 消费失败
*/
文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99
文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效
文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是
文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件
文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件
文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码
文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware
文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停
文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待
文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析
文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code
文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象