Code Analysis for Consumer Issues in Java
The content of this article is about code analysis of consumer issues in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Resource
public class Resource { //当前资源的数量 int num = 0; //当前资源的上限 int size = 10; //消费资源 public synchronized void remove() { //如果num为0,没有资源了,需要等待 while (num == 0) { try { System.out.println("消费者进入等待"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果线程可以执行到这里,说明资源里有资源可以消费 num--; System.out.println("消费者线程为:" + Thread.currentThread().getName() + "--资源数量:" + num); this.notifyAll(); } //生产资源 public synchronized void put() { //如果资源满了,就进入阻塞状态 while (num == size) { try { System.out.println("生产者进入等待"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num++; System.out.println("生产者线程为:" + Thread.currentThread().getName() + "--资源数量:" + num); this.notifyAll(); } }
2. Consumer
public class Consumer implements Runnable { private Resource resource; public Consumer(Resource resource) { this.resource = resource; } @Override public void run() { while (true){ resource.remove(); } } }
3. Producer
public class Producer implements Runnable { private Resource resource; public Producer(Resource resource){ this.resource=resource; } @Override public void run() { while (true){ resource.put(); } } }
4. Test
public class TestConsumerAndProducer { public static void main(String[] args) { Resource resource = new Resource(); //生产线程 Producer p1 = new Producer(resource); //消费线程 Consumer c1 = new Consumer(resource); new Thread(p1).start(); new Thread(c1).start(); } }
Related recommendations:
Detailed explanation of examples of java producers and consumers
Java multi-threaded concurrent collaborative producer consumption Design pattern
The above is the detailed content of Code Analysis for Consumer Issues in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Hello everyone, I am Brother Jun. Recently, a reader was asked a question during an interview. If a consumer pulls a batch of messages, such as 100 messages, and the 100th message is successfully consumed, but the 50th message fails, how will the offset be updated? Regarding this issue, let’s talk today about how to save the offset if a batch of messages fails to be consumed. 1 Pulling messages 1.1 Encapsulating pull requests Taking RocketMQ push mode as an example, the RocketMQ consumer startup code is as follows: public static void main(String[] args) throws InterruptedException, MQClie

Implementation Methods of Queue Producer and Consumer Patterns in PHP and MySQL With the rapid development of Internet business, the need to handle a large number of tasks in the system has become more and more urgent. Queues are a common solution to handle tasks efficiently. The implementation of the queue's producer-consumer pattern (Producer-ConsumerPattern) in PHP and MySQL is a common solution. This article will introduce the specific implementation method and provide code examples. producer-consumer pattern

A prevalent synchronization challenge in concurrent computing is known as the producer-consumer problem. Given that multiple threads or processes are designed to coordinate their operations when accessing a shared source; this problem requires complex communication tasks as well as balanced execution. Today's discussion will help to understand the concepts behind this difficulty, while recognizing its importance in contemporary computer science frameworks - particularly in C++ implementation practice. Understanding the Definition and Purpose of the Producer-Consumer Problem Solutions to the challenges posed by the producer-consumer problem come from clearly demarcating responsibilities between those responsible for producing and using information. When producers generate new records themselves, consumers ensure they are used correctly by synchronizing their operations. One must be careful to avoid problems such as race conditions or deadlocks, e.g.

Qualcomm has launched its latest mobile platform, Qualcomm Snapdragon 4Gen 2. This new processor and platform are designed for value smartphones and we can expect to see it used in smartphones in the second half of 2023. Qualcomm Technologies has announced the launch of the new Snapdragon 4 Gen 2 mobile platform, which is creatively designed to provide incredible mobile experiences to more consumers around the world. Snapdragon 4Gen 2 delivers effortless all-day use, with fast CPU speeds, crisp photography and videography, and fast 5G and Wi-Fi for reliable connectivity. ® "Snapdragon - at its core - is driving innovation while meeting the needs of OEMs and the broader industry," Matthew Lop, director of product management, Qualcomm Technologies

A new survey from Cisco shows that consumers support artificial intelligence but are concerned about how businesses use the technology, with more than half of respondents saying they have lost trust in their organizations due to the use of artificial intelligence. The data was disclosed in Cisco's 2022 Consumer Privacy Survey, an annual global review of consumer perceptions and behaviors around data privacy. This year’s survey highlights the need for further transparency, as consumers say their top priority is for organizations to be more transparent about how they use their personal data. The Cisco survey also showed that while consumers support AI (54% are willing to share their anonymized data to improve AI products), 65% have lost trust in organizations due to the use of AI. "enterprise

Smart officially released a new rights adjustment announcement for the Smart Elf #1Pulse Heartbeat Edition today, providing consumers with more car purchasing benefits. According to the announcement, consumers who purchase the Smart Elf #1Pulse version from August 16 to August 31, 2023 will enjoy a series of generous car purchasing benefits, which not only provides more benefits to car lovers, but also further enhances It is understood that the new car purchase rights adjustment plan includes multiple benefits, one of which is the vehicle final payment deduction right. Car buyers can enjoy a deduction of up to 10,000 yuan on the final payment, alleviating some of the financial pressure. In addition, the official also provides free upgrade rights, including the close friend atmosphere group set

According to news on September 5, Huawei’s latest flagship mobile phone series, Huawei Mate60 series, has caused a sensation in the Chinese Internet world. This series of mobile phones has not only attracted much attention in the market, but also won a high degree of love and respect in the hearts of consumers. Recently, Huawei stores have started selling the Mate60 series, and consumers from all over the world have flocked to the stores and queued up. One enthusiastic consumer even sent a banner to Huawei's mobile phone flagship store with the words "Far Ahead", which is a sign of respect for Huawei's breakthrough and innovation in the face of adversity. According to the editor's understanding, Huawei Mate60Pro went on sale online and offline on September 3, and was sold out almost instantly on multiple online channels such as JD.com, Tmall, and Huawei Mall. According to Huawei’s official website, Mate

This website reported on July 2 that the "Regulations on the Implementation of the Consumer Rights Protection Law of the People's Republic of China" will come into effect on July 1. This site learned from the official website of the China Consumers Association that the China Consumers Association has developed the WeChat mini program operator side of the "National Consumers Association Smart 315 Platform" (referred to as "Consumers Association 315") platform and has been online since July 1 . The China Consumers Association stated that the "Consumers Association 315" operator terminal has the following functions: Search the "Consumers Association 315" applet through WeChat and easily log into the platform to receive consumer complaints on the mobile terminal and support online handling, online reconciliation and operation on the mobile terminal. The "Consumers Association 315" platform with many functions such as user management will be launched for trial operation on March 15, 2024. By the end of June 2024, more than 17,000 operators will have settled in
