Java multithreading--producer and consumer issues

Source: Internet
Author: User

Description

In Java, the communication between threads is mainly done by the 3 methods of wait,notify , and Notifyall provided by the Java.lang.Object class:

After the wait method of the ① object is called, the thread enters the object's wait queue, frees the object lock, and other threads can compete to use this object lock; Thesleep method puts a thread to sleep, but the resources that the thread occupies are not released.

② when an object's notify method is called, the method takes a random thread from the object's waiting queue to wake up, andNotifyall is the wake-up waiting queue for all the threads that are competing with other executing threads for object locks.

the 3 methods of ③wait,notify and Notifyall can only appear within the scope of the synchronized effect. The Notifyall method should be used when multiple threads wait for the same object while they wait for a different condition. Notifyall can cause performance degradation because unnecessary threads are also awakened. The thread that notify wakes up may not be the expected thread.


Producer and consumer issues

Here, the thread that uses a class of resources (represented by class goods) is called the consumer consumer, and the thread that produces the same resource is called producer. To enable consumer and producer to work together, they should follow the following rules:

(1) The producer producer can store the resources as long as buffer buffers have space, and when buffer buffers are full, let the producer producer Wait, discard the acquired object lock and enter the waiting queue;

(2) As long as there is a resource available in the buffer, the consumer consumer can remove the resource from buffer, and when buffer is empty, let consumer wait, discard the acquired object lock and enter the waiting queue;

(3) Producer and consumer cannot read and write buffer at the same time. So the way to operate on buffer increase (production resources) and decrease (consumer resources) need to be synchronized using synchronized.


/** * Goods class, representing shared resources */package Com.hh.producer.consumer;public class Goods {private final int SIZE = 5;private int buffer = 0;/** * Shared resources increased */public synchronized int increase () {if (buffer < SIZE) {++buffer;notify ();//Notify consumers to consume} else {try {W AIT (); The creator thread waits until the consumer thread issues a NOTIFY notification} catch (Interruptedexception e) {e.printstacktrace ();}} return buffer;}  /** * Shared resources reduced */public synchronized int decrease () {if (Buffer > 0) {--buffer;notify ();//notify producer to produce} else {try {wait (); The consumer thread waits until the producer thread issues a NOTIFY notification} catch (Interruptedexception e) {e.printstacktrace ();}} return buffer;} public int getgoodssize () {return SIZE;}}


/** * Producer class, analog producer thread */package Com.hh.producer.consumer;public class Producer implements Runnable {private Goods Goods ;p ublic Producer (Goods Goods) {this.goods = Goods;} @Overridepublic void Run () {while (true) {int goodscount = Goods.increase (); if (Goodscount! = Goods.getgoodssize ()) {Syste M.out.println ("producer produces a commodity, the current number of goods:" + Goodscount);} else {System.out.println ("The product is full, the producer Waits");} try {thread.sleep (int) (Math.random () *)} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.prin Tstacktrace ();}}}

/** * Consumer class, Analog consumer */package Com.hh.producer.consumer;public class Consumer implements Runnable {private Goods goods;p Ublic Consumer (Goods Goods) {this.goods = Goods;} @Overridepublic void Run () {while (true) {int goodscount = Goods.decrease (); if (Goodscount! = 0) {System.out.println ("consumer Cost a commodity, the current number of goods: "+ Goodscount);} else {System.out.println ("product is empty, consumer Waits");} try {thread.sleep (int) (Math.random () *)} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.prin Tstacktrace ();}}}

/** * Test the communication between producer Producer and consumer Consumer thread */package Com.hh.producer.consumer;public class Testmain {public static void main (string[] args) {Goods Goods = new Goods (); Producer Producer = new Producer (goods); Consumer Consumer = new Consumer (goods); new Thread (producer). Start (); new Thread (Consumer). Start ();}

Note: The wait and notify operations are performed in the shared resources goods class, not in the producer or consumer class.

For such a problem, be sure to write the sample code yourself, so that you can better understand the communication between the threads problem.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.