当前位置:网站首页>Multithreading (threaded Communication [producer and consumer])
Multithreading (threaded Communication [producer and consumer])
2022-04-22 07:49:00 【PkyShare】
1 Producer consumer
Threads are not independent of each other , They need to communicate and collaborate with each other , The most typical example is the producer - Consumer issues .
Suppose there is only one product in the warehouse , The products produced by the producer are put into the warehouse , Consumers take products from the warehouse .
If there is no product in the warehouse , Then the producer puts the product in the warehouse , Otherwise stop production and wait , Until the products in the warehouse are taken away by consumers .
If there are products in the warehouse , Then the consumer takes the product away , Otherwise, stop consumption and wait .
The process of communicating with each other is Thread collaboration .

2 wait/notify Realization
Thread communication can be through wait and notify or notifyAll To implement .
- wait() : Let the current thread release the object lock and enter the wait ( Blocking ) state .
- notify(): Wake up a thread waiting for the corresponding object lock , Put it in the ready queue , In order to compete for the lock after the current thread releases the lock , And then you get CPU Implementation .
- notifyAll(): Wake up all threads waiting for the corresponding object lock , Put them in the ready queue , In order to compete for the lock after the current thread releases the lock , And then you get CPU Implementation .
First of all, we should sort out what we need : producer 、 product 、 consumer 、 Warehouse .
2.1 producer
public class Producer extends Thread {
Warehouse warehouse; // Warehouse
public Producer(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
// Produce products and put them in the warehouse
for(int i = 0; i < 100; i++) {
warehouse.push(new Product(i));
System.out.println(" Produced " + (i + 1) + " Product No ");
}
}
}
2.2 product
/** * product */
public class Product {
private Integer id; // goods id
public Product(Integer id) {
this.id = id;
}
/** * Get product ID * @return */
public Integer getId() {
return this.id;
}
}
2.3 consumer
public class Consumer extends Thread {
Warehouse warehouse; // Warehouse
public Consumer(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
// Consumer products
for(int i = 0; i < 100; i++) {
Product product = warehouse.pop();
System.out.println(" The consumption " + product.getId()+ " Product No ");
}
}
}
2.4 Warehouse
/** * Warehouse */
public class Warehouse {
private Product[] products = new Product[10]; // Commodity queue
private int count = 0; // Queue counter
/** * Put the product * @param product */
public synchronized void push(Product product) {
// If the line of goods is full , Need to wait for consumers to spend
if(count == 10) {
try {
this.wait();
}
catch (Exception e) {
e.printStackTrace();
}
}
// If it's not full , Put it in the queue
products[count] = product;
count++;
// Inform consumers of consumption
this.notifyAll();
}
/** * Consumer products */
public synchronized Product pop() {
// If the product queue is gone , Need to wait for the producer to produce
if(count == 0) {
try {
this.wait();
}
catch (Exception e) {
e.printStackTrace();
}
}
count--;
Product product = products[count];
// Inform the producer to produce
this.notifyAll();
return product;
}
}
2.5 test
public class MainTest {
public static void main(String[] args) throws Exception {
Warehouse warehouse = new Warehouse(); // Create repository
new Producer(warehouse).start(); // Create the producer thread and start it
new Consumer(warehouse).start(); // Create and launch the consumer thread
}
}
Console output
Produced 1 Product No Produced 2 Product No Produced 3 Product No Produced 4 Product No Produced 5 Product No Produced 6 Product No Produced 7 Product No Produced 8 Product No Produced 9 Product No Produced 10 Product No The consumption 9 Product No The consumption 8 Product No The consumption 7 Product No The consumption 6 Product No The consumption 5 Product No Produced 11 Product NoIt can be seen that , Sir gave birth 10 Products , Start consuming when the queue is full , When the queue is not full, start production again .
版权声明
本文为[PkyShare]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220622134567.html
边栏推荐
- PWA 我来了
- JWT实现登录认证,密码加密及Token校验全过程(附源码)
- Information System Project Manager --- Chapter IV examination questions of overall project management over the years
- 接口的应用与定义
- unity面试题附一个(网上商城)
- C-11 Problem I: 找气球
- 某英语网不允许粘贴的原理及解决方法
- 运行程序~自定义类似CMD命令打开非系统软件
- @ transactional transaction propagation in the same class
- Crawler learning 2 - requests module - get request mode
猜你喜欢

多线程(线程通信【生产者与消费者】)

7-1金融介绍

Database addition, deletion, modification and query

Strong net cup 2019 random note

Information System Project Manager - Chapter IV overall project management

Deep understanding of MySQL (7): how to tune MySQL

UNITY遮罩点击下层UI游戏开始引导点击

可视化编程——绘图篇作业

JWT实现登录认证,密码加密及Token校验全过程(附源码)

Oracle unique index
随机推荐
IDEA的下载和配置
ActiveMQ的消息模式——队列模式
运行程序~自定义类似CMD命令打开非系统软件
redis 缓存穿透和雪崩
Access modifier
依赖冲突查找与解决办法(以EasyPoi为例,出现 NoSuchMethodError 或 NoClassDefFoundError )
小程序 - canvas绘制海报
百钱买百鸡
Unity 知识点(常用核心类)
可视化编程——绘图篇作业
ES6 notes
多线程(Thread 类、Runnable 接口、Callable 接口、synchronized 、Lock、线程池)
APC (II)
7-2 Tushare
数据库高级查询(2)
小程序 - 超过两件折叠展开逻辑
Opportunity interview questions
Saltstack practice
Centos7 initialization script for automated operation and maintenance
数组的定义格式