Java并发编程实例--15.在同步代码块中使用条件
并发编程中有个经典问题:
生产消费者问题。
我们有一个数据缓冲区,一个或多个生产者往其中存入对象,另外一个或多个消费者从中取走。
因此,该数据缓冲区是一个共享数据结构,我们需要对其添加读取同步机制,但是我们还需要一些限制。
如果缓冲区满了,生产者不能继续向其中写入;反过来如果缓冲区空了,消费者也不能继续读取。
对于这种情况,Java提供了wait(),notify()和notifyAll()方法。
一个线程可以在同步代码块中调用wait()方法。如果它在同步块之外调用wait()方法,JVM将抛出IllegalMonitorStateException。
当线程调用wait()方法,JVM将该线程睡眠并且释放控制同步代码块的对象,并允许其他线程去执行。
如果需要再次唤醒该线程,只需要调用notify()或notifyAll()方法。
本例中,你将学习如何使用synchronized关键字和wait(), notify(), and notifyAll()方法去实现生产-消费者问题。
缓冲区类:
EventStorage.java
package com.dylan.thread.ch2.c03.task;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/**
* This class implements an Event storage. Producers will storage
* events in it and Consumers will process them. An event will
* be a java.util.Date object
*
*/
public class EventStorage {
/**
* Maximum size of the storage
*/
private int maxSize;
/**
* Storage of events
*/
private List<Date> storage;
/**
* Constructor of the class. Initializes the attributes.
*/
public EventStorage(){
maxSize=10;
storage=new LinkedList<>();
}
/**
* This method creates and storage an event.
*/
public synchronized void set(){
while (storage.size()==maxSize){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.add(new Date());
System.out.printf("Set: %d",storage.size());
notify();
}
/**
* This method delete the first event of the storage.
*/
public synchronized void get(){
while (storage.size()==0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("Get: %d: %s",storage.size(),((LinkedList<?>)storage).poll());
notify();
}
}
生产者:
Producer.java
package com.dylan.thread.ch2.c03.task;
/**
* This class implements a producer of events.
*
*/
public class Producer implements Runnable {
/**
* Store to work with
*/
private EventStorage storage;
/**
* Constructor of the class. Initialize the storage.
* @param storage The store to work with
*/
public Producer(EventStorage storage){
this.storage=storage;
}
/**
* Core method of the producer. Generates 100 events.
*/
@Override
public void run() {
for (int i=0; i<100; i++){
storage.set();
}
}
}
消费者:
Consumer.java
package com.dylan.thread.ch2.c03.task;
/**
* This class implements a consumer of events.
*
*/
public class Consumer implements Runnable {
/**
* Store to work with
*/
private EventStorage storage;
/**
* Constructor of the class. Initialize the storage
* @param storage The store to work with
*/
public Consumer(EventStorage storage){
this.storage=storage;
}
/**
* Core method for the consumer. Consume 100 events
*/
@Override
public void run() {
for (int i=0; i<100; i++){
storage.get();
}
}
}
主类:
Main.java
package com.dylan.thread.ch2.c03.core;
import com.dylan.thread.ch2.c03.task.Consumer;
import com.dylan.thread.ch2.c03.task.EventStorage;
import com.dylan.thread.ch2.c03.task.Producer;
/**
* Main class of the example
*/
public class Main {
/**
* Main method of the example
*/
public static void main(String[] args) {
// Creates an event storage
EventStorage storage=new EventStorage();
// Creates a Producer and a Thread to run it
Producer producer=new Producer(storage);
Thread thread1=new Thread(producer);
// Creates a Consumer and a Thread to run it
Consumer consumer=new Consumer(storage);
Thread thread2=new Thread(consumer);
// Starts the thread
thread2.start();
thread1.start();
}
}
运行结果:
Set: 1
Set: 2
Set: 3
Set: 4
Set: 5
Set: 6
Set: 7
Set: 8
Set: 9
Set: 10
Get: 10: Fri May 11 22:31:02 GMT+08:00 2018
Get: 9: Fri May 11 22:31:02 GMT+08:00 2018
Get: 8: Fri May 11 22:31:02 GMT+08:00 2018
Get: 7: Fri May 11 22:31:02 GMT+08:00 2018
Get: 6: Fri May 11 22:31:02 GMT+08:00 2018
Get: 5: Fri May 11 22:31:02 GMT+08:00 2018
Get: 4: Fri May 11 22:31:02 GMT+08:00 2018
Get: 3: Fri May 11 22:31:02 GMT+08:00 2018
Get: 2: Fri May 11 22:31:02 GMT+08:00 2018
Get: 1: Fri May 11 22:31:02 GMT+08:00 2018
Set: 1
Set: 2
...
Java并发编程实例--15.在同步代码块中使用条件的更多相关文章
- Java并发编程:线程的同步
Java并发编程:线程的同步 */--> code {color: #FF0000} pre.src {background-color: #002b36; color: #839496;} J ...
- Java并发编程的4个同步辅助类
Java并发编程的4个同步辅助类(CountDownLatch.CyclicBarrier.Semphore.Phaser) @https://www.cnblogs.com/lizhangyong/ ...
- Java并发编程系列-(9) JDK 8/9/10中的并发
9.1 CompletableFuture CompletableFuture是JDK 8中引入的工具类,实现了Future接口,对以往的FutureTask的功能进行了增强. 手动设置完成状态 Co ...
- “全栈2019”Java多线程第二十一章:同步代码块产生死锁的例子
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...
- “全栈2019”Java多线程第十八章:同步代码块双重判断详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...
- .NET中如何在同步代码块中调用异步方法
更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 在同步代码块中调用异步方法,方法有很多. 一.对于有返回值的Task 在同步代码块中直接访问 Task 的 Result ...
- wait、notify为什么要放在同步代码块中
等待方遵循的原则: 获取对象的锁,不满足条件就调用wait()方法,条件满足继续执行 通知方原则: 获取对象的锁,改变条件,然后notify 每个对象都有一个监视器锁,这个监视器锁的数据结构如下: w ...
- Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semphore、Phaser)
我在<jdk1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...
- Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semaphore、Phaser)
我在<JDK1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...
- Java并发编程(十三)同步容器类
同步容器类 Vector.HashTable,我用的很少:Vecotr的实现和ArrayList挺接近的,不同的是Vector中很多的方法都用synchronized进行了同步.在不强调线程安全地时候 ...
随机推荐
- [转帖]解决Harbor在服务器重启后无法自启动的问题
问题 当部署Harbor的服务器在重启之后,可能会出现Harbor无法跟随系统自启动 解决方案 现假设Harbor的安装目录位置为/usr/local/harbor,在Harbor安装完成之后,在此目 ...
- [转帖]Linux—微服务启停shell脚本编写模板
https://www.jianshu.com/p/1e1080a39dc5 run.sh #!/bin/bash if [ -s java.pid ] then echo "重复启动,退出 ...
- 【转帖】Linux 系统双网卡绑定 bond的7种模式
第一种模式:mod=0 ,即:(balance-rr) Round-robin policy(平衡抡循环策略)第二种模式:mod=1,即: (active-backup) Active-backup ...
- 【转帖】网卡bonding模式 - bond0、1、4配置
网卡bonding简介 网卡绑定就是把多张物理网卡通过软件虚拟成一个虚拟的网卡,配置完毕后,所有的物理网卡的ip和mac将会变成相同的.多网卡同时工作可以提高网络速度,还可以实现网卡的负载均衡.冗余. ...
- 【转帖】在ECS上配置skywalking-nginx-lua
https://help.aliyun.com/document_detail/197660.html 此处以在CentOS 7.0上的操作为例. 配置Lua运行环境. 安装工具库. yum in ...
- SPECCPU2006的学习与使用
SPECCPU2006的学习与使用 摘要 这个周末问题不是很多, 陪孩子写作业时顺便研究了下SPEC2006 虽然比较落后了. 但是总比没有要强一些. 其实集团有资源, 但是联系不到人, 只能自己学习 ...
- 【k哥爬虫普法】Python程序员爬取视频资源13万部,一分钱没挣,获刑2年!
我国目前并未出台专门针对网络爬虫技术的法律规范,但在司法实践中,相关判决已屡见不鲜,K 哥特设了"K哥爬虫普法"专栏,本栏目通过对真实案例的分析,旨在提高广大爬虫工程师的法律意识, ...
- 2021美亚杯团队赛write up
个人赛与团队赛下载文件解压密码:MeiyaCup2021 加密容器解密密码: uR%{)Y'Qz-n3oGU`ZJo@(1ntxp8U1+bW;JlZH^I4%0rxf;[N+eQ)Lolrw& ...
- gin启动https支持
gin是一个使用Go语言开发的Web框架,具有运行速度快,分组的路由器,良好的崩溃捕获和错误处理,支持中间件等. 在工作中有时候需要支持https服务,gin可以通过中间件的方式来提供对https的支 ...
- 给你一颗“定心丸”——记一次由线上事故引发的Log4j2日志异步打印优化分析
一.内容提要 自知是人外有人,天外有天,相信对于Log4j2的异步日志打印早有老师或者同学已是熟稔于心,优化配置更是信手拈来,为了防止我在这里啰里八嗦的班门弄斧,我先将谜底在此公布:log4j2.as ...