当前位置:网站首页>Producer consumer mode (multithreading, use of shared resources)
Producer consumer mode (multithreading, use of shared resources)
2022-07-03 20:20:00 【Chen4852010】
1.BlockingQueue( Blocking queues ) yes java A common container in , It is widely used in multithreaded programming . When the queue container is full, the producer thread is blocked , Do not continue until the queue is not full put; When the queue container is empty , Consumer thread blocked , You cannot continue until the queue is not empty take.
We use blocking queues as shared resources
public class Producer implements Runnable {
private final BlockingQueue<KouZhao> blockingQueue;
public Producer(BlockingQueue<KouZhao> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
if (blockingQueue.remainingCapacity() > 0) {
KouZhao kouZhao = new KouZhao(UUID.randomUUID().toString(), "N95");
blockingQueue.add(kouZhao);
System.out.println(" I'm making masks , The current inventory is :" + blockingQueue.size());
}
else {
System.out.println(" My warehouse is full " + blockingQueue.size() + " Masks , Come and buy a mask !");
}
} catch (InterruptedException e) {
e.printStackTrace(); }
}
}
}
public class Consumer implements Runnable {
private final BlockingQueue<KouZhao> blockingQueue;
public Consumer(BlockingQueue<KouZhao> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
long startTime = System.currentTimeMillis(); // Get start time
KouZhao kouZhao = blockingQueue.take();
long endTime = System.currentTimeMillis(); // Get the end time
System.out.println(" I consumed masks :" + kouZhao + ", When the goods arrive, I'll stop It's jammed " + (endTime - startTime) + "ms");
} catch (InterruptedException e) {
e.printStackTrace(); }
}
}
}
Now the point is , How to be in producer and comsumer In two threads Have shared resources
First of all, these two run Threads , Resources available now ,producer and consumer Inside the object blockingQueue,
Because although two threads are opened (run Is the thread ID ), But the first method stack of thread , Also called Of these two objects , Example method run( In the instance method, you can get , Of the instance properties of the object )
be equal to run Threads ( It's just a sign , A stack space ) and run In the thread producer Of example run Method The difference between
therefore as long as producer and consumer Inside the object blockingQueue, Point to the same blockingQueue that will do
So as long as it's in establish producer and consumer When the object , Pass them the same blockingQueue that will do
public class App {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<KouZhao> queue = new ArrayBlockingQueue<>(20);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
// To start a run Threads ( The identification of the thread is run), The main method stack is producer Of run Method
new Thread(producer).start();
Thread.sleep(20000);
// To start a run Threads ( The identification of the thread is run), The main method stack is producer Of run Method
new Thread(consumer).start();
}
}
Obviously, the above code cannot be put into the production environment , For example, there is no cluster , No distribution , The playing method is too single , Cannot satisfy the enterprise
Requirements for class a Applications ...
such as :
Is the message persistent ?
How to make sure that the message will be sent successfully ?
How to make sure that the message will be consumed successfully ?
How about the performance of high-speed parallel delivery ?
Is the system reliable ?
Is there any Pub/Sub Pattern ?
Has current limiting been considered ?
...
边栏推荐
- Basic command of IP address configuration ---ip V4
- Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
- Test changes in Devops mode -- learning and thinking
- BOC protected phenylalanine zinc porphyrin (Zn · TAPP Phe BOC) / iron porphyrin (Fe · TAPP Phe BOC) / nickel porphyrin (Ni · TAPP Phe BOC) / manganese porphyrin (Mn · TAPP Phe BOC) Qiyue Keke
- Global and Chinese market of high purity copper foil 2022-2028: Research Report on technology, participants, trends, market size and share
- Exercises of function recursion
- Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
- The 15 year old interviewer will teach you four unique skills that you must pass the interview
- Golang type assertion and conversion (and strconv package)
- MySQL learning notes - single table query
猜你喜欢

Promethus

Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro

2.7 format output of values

It is discussed that the success of Vit lies not in attention. Shiftvit uses the precision of swing transformer to outperform the speed of RESNET

AcWing 1460. Where am i?
![[effective Objective-C] - block and grand central distribution](/img/09/22b979b97ea13d649b4b904637b79f.jpg)
[effective Objective-C] - block and grand central distribution

44. Concurrent programming theory

原生表格-滚动-合并功能

Wechat applet quick start (including NPM package use and mobx status management)

Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
随机推荐
[Yugong series] February 2022 Net architecture class 004 ABP vNext used in WPF project
Professional interpretation | how to become an SQL developer
Deep search DFS + wide search BFS + traversal of trees and graphs + topological sequence (template article acwing)
MySQL learning notes - single table query
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
An old programmer gave it to college students
Pat grade B 1009 is ironic (20 points)
Nacos usage of micro services
About callback function and hook function
How to read the source code [debug and observe the source code]
The 29th day of force deduction (DP topic)
Global and Chinese market of rubidium standard 2022-2028: Research Report on technology, participants, trends, market size and share
Example of peanut shell inner net penetration
Battle drag method 1: moderately optimistic, build self-confidence (1)
Global and Chinese market of micro positioning technology 2022-2028: Research Report on technology, participants, trends, market size and share
Find a line in a file and remove it
Test access criteria
[Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
Q&A:Transformer, Bert, ELMO, GPT, VIT
你真的知道自己多大了吗?