A producer, two consumers, Max=1,
There is a moment when all the threads are entering the waiting queue.
To resolve the deadlock problem, see the following code:
Package java.thread;
/** * Deadlock problem in production and consumption * * public class ThreadDemo6 {public static void main (string[] args) {//Use Java Collection class, List is lists.
Pool1 pool = new Pool1 ();
Productor P1 = new Productor ("Producer 1", pool);
P1.setname ("P1");
Consumer1 C1 = new Consumer1 ("Consumer", pool);
C1.setname ("C1");
Consumer1 C2 = new Consumer1 ("Consumer", pool);
C2.setname ("C2");
P1.start ();
C1.start ();
C2.start ();
}//Producer class Productor extends Thread {static int i = 0;
private String name;
Private Pool1 pool;
Public Productor (String name, Pool1 pool) {this.name = name;
This.pool = pool;
public void Run () {while (true) {Pool.add (i++);
}}//Consumer class Consumer1 extends Thread {private String name;
Private Pool1 pool;
Public Consumer1 (String name, Pool1 pool) {this.name = name;
This.pool = pool;
public void Run () {while (true) {pool.remove ();
System.out.println ("-:" + i); }}/** * Pool/class Pool1 {private Java.util.list<integer> list = new java.util.arraylist<integer> ();
container maximum value private int MAX = 1;
add element public void Add (int n) {synchronized (this) {try {String name = Thread.CurrentThread (). GetName ();
while (list.size () = = MAX) {System.out.println (name + ". Wait ()");
Timed waiting.
This.wait ();
} list.add (n);
SYSTEM.OUT.PRINTLN (name + "+:" + N);
SYSTEM.OUT.PRINTLN (name + ". Notify ()");
This.notifyall ();
catch (Exception e) {e.printstacktrace (); "}}//delete element public int remove () {synchronized () {try {String name = Thread.CurrentThread (). GetName
();
while (list.size () = = 0) {System.out.println (name + ". Wait ()");
This.wait ();
int i = list.remove (0);
SYSTEM.OUT.PRINTLN (name + "-:" + i);
SYSTEM.OUT.PRINTLN (name + ". Notify ()");
This.notifyall ();
return i;
catch (Exception e) {e.printstacktrace ();
} return-1; }
}
}