Today read a blog, talk about the Java multi-thread threads collaboration, wherein the author uses the program example to explain the producer and consumer issues, but I and other readers found that the program run more than a few times there will be a deadlock, Baidu searched the majority of the examples are also bug, after careful study found the problem, and resolved, Feel the meaning to post it and share it.
The following is the first to post a bug code, a 4 class, Plate.java:
Package Creatorandconsumer;import java.util.arraylist;import java.util.list;/** * Tray, representing shared resources * @author Martin * */public Class Plate {private list<object> eggs = new arraylist<object> ();/** * Get egg * @return */public Object Getegg () { SYSTEM.OUT.PRINTLN ("Consumers take Eggs"), Object egg = eggs.get (0); eggs.remove (0); return egg;} /** * Add egg * @return */public void Addegg (Object egg) {System.out.println ("producer Raw egg"); Eggs.add (egg);} /** * Get the number of eggs * @return */public int geteggnum () {return eggs.size ();}}
Consumer class: Consumer2.java
Package Creatorandconsumer;public class Consumer2 implements Runnable {/** * thread resources */private Plate plate;public Consumer2 (P Late plate) {this.plate = plate;} @Overridepublic void Run () {synchronized (plate) {//If the number of eggs at this time is greater than 0, then the while (Plate.geteggnum () < 1) {try {///This detail requires attention if the line Process into wait, then the lock on it will be temporarily released,//otherwise the thread will not be locked, and then wake up this thread plate.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} After wake up, get the resource lock again, and the condition satisfies can safely take the Egg Plate.getegg ();p late.notify ();}}
Producer class: Creator2.java
Package creatorandconsumer;/** * Producer * * @author Martin * */public class Creator2 implements Runnable {/** * thread resource */private Plate plate;public Creator2 (Plate Plate) {this.plate = Plate;} @Overridepublic void Run () {synchronized (plate) {//If the number of eggs at this time is greater than 0, then the while (Plate.geteggnum () >= 5) {try {///This detail requires attention if The thread enters wait, then the lock on it will be released temporarily,//otherwise the thread will not be able to lock, then wake the thread plate.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} After wake up, get the resource lock again, and the condition is satisfied can be assured that the egg, object egg = new Object ();p Late.addegg (egg);p late.notify ();}}
Test class: Tester.java
Package Creatorandconsumer;public class Tester {public static void main (string[] args) {//shared resource plate plate = new plate ();//Tim Add producer and consumer for (int i = 0; i <; i + +) {//Bug version new Thread (new CREATOR2 (plate)). Start (); New Thread (New CONSUMER2 (plate)). Start ();//Bug-free version//new Thread (new Creator (plate)). Start ();//new Thread (New Consumer (plate)). Start ();}}
If you run multiple times or change the number of loops in the test class, you will find that the probability of a deadlock is still high. The following is an analysis of why this problem occurs:
There is an explanation for object.wait in the JDK: the current thread must have this object monitor. The thread discards ownership of this monitor and waits until other threads wake up by calling the Notify method, or the Notifyall method notifies the thread waiting on this object's monitor. It can be seen that the following situation may occur: the consumer 1 into the waiting state (at this time the resource lock has been released), if the consumer 2 access to the resource synchronization lock (no one to ensure that consumers 1 into the waiting, the next to get the lock must be the producer), the consumer 2 Judge no resources also enter the waiting state At this time, producer 1 production, and notify Consumer 1, consumer 1 smoothly consumed, and perform notify operation, but at this time the consumer 2 is also because of resources and in the waiting state, thus awakened the consumer 2 (consumer 1 to awaken other producers), and at this time there is no resources, Led to the entire program because the consumer 2 into an infinite wait, forming a deadlock.
After the above analysis, the fundamental reason is: at the same time several consumers or several producers in the waiting state, resulting in consumers may wake up or consumers, or producers wake up or producer. So if we can guarantee that only one consumer is in the wait state at the same time (the producer is the same), then we can ensure that the consumer wakes up must be the producer, so that the whole task will go on smoothly. The following is the modified code:
Improved Consumer. java
Package Creatorandconsumer;public class Consumer implements Runnable {/** * thread resource */private Plate plate;/** * producer Lock: Used to lock the same time Only one producer can enter the production critical area (if at the same time two producers enter the critical section, it is likely that one of the producers would have awakened the consumer but awakened the producer) */private static Object consumerlocker = new Object (); Public Consumer (Plate Plate) {this.plate = Plate;} @Overridepublic void Run () {//must first obtain a producer lock to produce synchronized (Consumerlocker) {synchronized (plate) {///If the number of eggs at this time is greater than 0, Then the while (Plate.geteggnum () < 1) {try {///This detail needs to be noted that if the thread enters wait, then the lock on it will be released temporarily,//otherwise the other thread will not be able to lock, then wake up this thread plate.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} After wake up, get the resource lock again, and the condition is satisfied can safely take the Egg Plate.getegg ();p late.notify ();}}}
Improved Creator.java:
Package creatorandconsumer;/** * Producer * * @author Martin * */public class Creator implements Runnable {/** * thread resource * /private Plate plate;/** * producer Lock: For locking at the same time only one producer can enter the production critical area (if both producers enter the critical section, it is likely that one of the producers would have awakened the consumer but awakened the producer) */private Static Object Creatorlocker = new Object ();p ublic Creator (Plate Plate) {this.plate = Plate;} @Overridepublic void Run () {//must obtain a producer lock before production synchronized (Creatorlocker) {synchronized (plate) {///If the number of eggs at this time is greater than 0, then wait (Plate.geteggnum () >= 5) {try {//This detail needs to be noted that if the thread enters wait, then the lock on it will be released temporarily,//otherwise the thread will not be able to lock, then wake the thread plate.wait ();} catch (Interruptedexception e) { E.printstacktrace ();}} After wake up, get the resource lock again, and the condition is satisfied can be assured that the egg, object egg = new Object ();p Late.addegg (egg);p late.notify ();}}}
Improvement Note: The improved producer and consumer have added producer and consumer locks, respectively, for locking at the same time only one consumer (producer) enters the production critical area (if simultaneously two producers enter the critical section, it is likely that one of the producers would have awakened the consumer but awakened the producer), In general there are altogether three locks: consumer Lock, producer lock, producer and consumer shared lock.
Finally, when you write multithreading, it is important to note that a resource can wake up all the threads that are waiting for that resource, so the consumer thread does not necessarily wake up either the producer thread or the consumer thread.
Java Multithreading: A better solution for producer consumers (make sure there are no deadlocks)