一个生产者,两个消费者,MAX=1,
有一个时刻,所有的线程都进入等待队列。
解决死锁问题,见以下代码:
package java.thread;
/**
* 生产消费中的死锁问题
*/
public class ThreadDemo6 {
public static void main(String[] args) {
//使用java中集合类,List是列表。
Pool1 pool = new Pool1();
Productor p1 = new Productor("生产者1", pool);
p1.setName("p1");
Consumer1 c1 = new Consumer1("消费者", pool);
c1.setName("c1");
Consumer1 c2 = new Consumer1("消费者", pool);
c2.setName("c2");
p1.start();
c1.start();
c2.start();
}
}
//生产者
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++);
}
}
}
//消费者
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);
}
}
}
/**
* 池子
*/
class Pool1 {
private java.util.List<Integer> list = new java.util.ArrayList<Integer>();
//容器最大值
private int MAX = 1;
//添加元素
public void add(int n) {
synchronized (this) {
try {
String name = Thread.currentThread().getName();
while (list.size() == MAX) {
System.out.println(name + ".wait()");
//限时等待。
this.wait();
}
list.add(n);
System.out.println(name + " + : " + n);
System.out.println(name + ".notify()");
this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//删除元素
public int remove() {
synchronized (this) {
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;
}
}
}