当前位置:网站首页>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 ?
...
边栏推荐
- Oak-d raspberry pie cloud project [with detailed code]
- Nacos usage of micro services
- BOC protected alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC supplied by Qiyu
- unittest框架基本使用
- Global and Chinese markets of cast iron diaphragm valves 2022-2028: Research Report on technology, participants, trends, market size and share
- February 14-20, 2022 (osgear source code debugging +ue4 video +ogremain source code transcription)
- Wargames study notes -- Leviathan
- 【c】 Digital bomb
- Assign the CMD command execution result to a variable
- Machine learning support vector machine SVM
猜你喜欢

2.7 format output of values

Native table - scroll - merge function

Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!

Popularize the basics of IP routing

Network security Kali penetration learning how to get started with web penetration how to scan based on nmap

The 15 year old interviewer will teach you four unique skills that you must pass the interview

Wargames study notes -- Leviathan

Test changes in Devops mode -- learning and thinking

IP address is such an important knowledge that it's useless to listen to a younger student?

JMeter connection database
随机推荐
Exercises of function recursion
3. Data binding
MPLS configuration
2166. Design bit set
Virtual machine installation deepin system
JMeter connection database
Network security Kali penetration learning how to get started with web penetration how to scan based on nmap
App compliance
Parental delegation mechanism
Microservice knowledge sorting - search technology and automatic deployment technology
2.7 format output of values
Analysis of gas fee setting under eip1559
Detailed and not wordy. Share the win10 tutorial of computer reinstallation system
Native table - scroll - merge function
In 2021, the global revenue of thick film resistors was about $1537.3 million, and it is expected to reach $2118.7 million in 2028
Battle drag method 1: moderately optimistic, build self-confidence (1)
How to read the source code [debug and observe the source code]
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
AI enhanced safety monitoring project [with detailed code]
2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers