当前位置:网站首页>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 ?
...
边栏推荐
- FPGA learning notes: vivado 2019.1 project creation
- 5. MVVM model
- 2.6 formula calculation
- Test changes in Devops mode -- learning and thinking
- Q&A:Transformer, Bert, ELMO, GPT, VIT
- Microservice knowledge sorting - search technology and automatic deployment technology
- Global and Chinese market of high purity copper foil 2022-2028: Research Report on technology, participants, trends, market size and share
- Detailed and not wordy. Share the win10 tutorial of computer reinstallation system
- How to set the system volume programmatically- How to programmatically set the system volume?
- About callback function and hook function
猜你喜欢
Network security Kali penetration learning how to get started with web penetration how to scan based on nmap
thrift go
44. Concurrent programming theory
BOC protected tryptophan porphyrin compound (TAPP Trp BOC) Pink Solid 162.8mg supply - Qiyue supply
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
Change deepin to Alibaba image source
Make a simple text logo with DW
Task of gradle learning
Battle drag method 1: moderately optimistic, build self-confidence (1)
BOC protected tryptophan zinc porphyrin (Zn · TAPP Trp BOC) / copper porphyrin (Cu · TAPP Trp BOC) / cobalt porphyrin (cobalt · TAPP Trp BOC) / iron porphyrin (Fe · TAPP Trp BOC) / Qiyue supply
随机推荐
BOC protected tryptophan zinc porphyrin (Zn · TAPP Trp BOC) / copper porphyrin (Cu · TAPP Trp BOC) / cobalt porphyrin (cobalt · TAPP Trp BOC) / iron porphyrin (Fe · TAPP Trp BOC) / Qiyue supply
IP address is such an important knowledge that it's useless to listen to a younger student?
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
Class loading process
Battle drag method 1: moderately optimistic, build self-confidence (1)
How can the outside world get values when using nodejs to link MySQL
强基计划 数学相关书籍 推荐
[effective Objective-C] - block and grand central distribution
Bool blind note - score query
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
Recommendation of books related to strong foundation program mathematics
Oak-d raspberry pie cloud project [with detailed code]
Q&A:Transformer, Bert, ELMO, GPT, VIT
Fingerprint password lock based on Hal Library
What is the difference between a kill process and a close process- What are the differences between kill process and close process?
5. MVVM model
The 29th day of force deduction (DP topic)
thrift go
In 2021, the global general crop protection revenue was about $52750 million, and it is expected to reach $64730 million in 2028
February 14-20, 2022 (osgear source code debugging +ue4 video +ogremain source code transcription)