并发编程中有个经典问题:
生产消费者问题。

我们有一个数据缓冲区,一个或多个生产者往其中存入对象,另外一个或多个消费者从中取走。

因此,该数据缓冲区是一个共享数据结构,我们需要对其添加读取同步机制,但是我们还需要一些限制。

如果缓冲区满了,生产者不能继续向其中写入;反过来如果缓冲区空了,消费者也不能继续读取。





对于这种情况,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.在同步代码块中使用条件的更多相关文章

  1. Java并发编程:线程的同步

    Java并发编程:线程的同步 */--> code {color: #FF0000} pre.src {background-color: #002b36; color: #839496;} J ...

  2. Java并发编程的4个同步辅助类

    Java并发编程的4个同步辅助类(CountDownLatch.CyclicBarrier.Semphore.Phaser) @https://www.cnblogs.com/lizhangyong/ ...

  3. Java并发编程系列-(9) JDK 8/9/10中的并发

    9.1 CompletableFuture CompletableFuture是JDK 8中引入的工具类,实现了Future接口,对以往的FutureTask的功能进行了增强. 手动设置完成状态 Co ...

  4. “全栈2019”Java多线程第二十一章:同步代码块产生死锁的例子

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  5. “全栈2019”Java多线程第十八章:同步代码块双重判断详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  6. .NET中如何在同步代码块中调用异步方法

    更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 在同步代码块中调用异步方法,方法有很多. 一.对于有返回值的Task 在同步代码块中直接访问 Task 的 Result ...

  7. wait、notify为什么要放在同步代码块中

    等待方遵循的原则: 获取对象的锁,不满足条件就调用wait()方法,条件满足继续执行 通知方原则: 获取对象的锁,改变条件,然后notify 每个对象都有一个监视器锁,这个监视器锁的数据结构如下: w ...

  8. Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semphore、Phaser)

    我在<jdk1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...

  9. Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semaphore、Phaser)

    我在<JDK1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...

  10. Java并发编程(十三)同步容器类

    同步容器类 Vector.HashTable,我用的很少:Vecotr的实现和ArrayList挺接近的,不同的是Vector中很多的方法都用synchronized进行了同步.在不强调线程安全地时候 ...

随机推荐

  1. ONVIF网络摄像头(IPC)客户端开发—RTSP RTCP RTP加载H264视频流

    前言: RTSP,RTCP,RTP一般是一起使用,在FFmpeg和live555这些库中,它们为了更好的适用性,所以实现起来非常复杂,直接查看FFmpeg和Live555源代码来熟悉这些协议非常吃力, ...

  2. 【面试题精讲】你知道MySQL中有哪些隔离级别吗

    有时博客内容会有变动,首发博客是最新的,其他博客地址可能未同步,请认准https://blog.zysicyj.top 首发博客地址 系列文章地址 脏读(Dirty Read)是指一个事务读取到了另一 ...

  3. [转帖]Archery

    Archery SQL 审核查询平台          文档 | FAQ | Releases 功能清单 数据库 查询 审核 执行 备份 数据字典 慢日志 会话管理 账号管理 参数管理 数据归档 My ...

  4. [转帖]wiki Rust

    Rust[编辑] 维基百科,自由的百科全书       跳到导航跳到搜索   此条目介绍的是由Mozilla主导开发的编程语言.关于"rust"在英文中的本意,请见"铁锈 ...

  5. [转帖]神秘的backlog参数与TCP连接队列

    https://www.cnblogs.com/codelogs/p/16060820.html 简介# 这要从一次压测项目说起,那是我们公司的系统与另几家同行公司的系统做性能比拼,性能数据会直接影响 ...

  6. VOP 消息仓库演进之路|如何设计一个亿级企业消息平台

    作者:京东零售 李孟冬 VOP作为京东企业业务对外的API对接采购供应链解决方案平台,一直致力于从企业采购数字化领域出发,发挥京东数智化供应链能力,通过产业链上下游耦合与链接,有效助力企业客户的成本优 ...

  7. empty来显示暂无数据简直太好用,阻止用户复制文本user-select

    element-ui表格某一列无数据显示-- 很多时候,表格的某一列可能是没有数据的. 空着了不好看,ui小姐姐会说显示 -- 这个时候,小伙伴是怎么做的呢? 使用循环来判断是否为空,然后赋值为-- ...

  8. vue 路由守卫是否携带token

    //整个实例出来 配置路由守卫 const router = new Router({ //这里面是路由配置哈 }) router.beforeEach((to, from, next) => ...

  9. vm-storage在全部都是新metric情况下的写入性能测试

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 vm-storage中,写入索引的性能要比写入data p ...

  10. ORM-gorm

    ORM-gorm 官方文档 http://gorm.book.jasperxu.com/ https://learnku.com/docs/gorm/v2 gorm文档 gorm文档2