多线程 死锁 wait(int i) notifyAll()

时间:2022-11-14 22:53:42
public class ThreadDemo5 {
public static void main(String[] args){
Pool pool = new Pool();
Productors p1 = new Productors(pool);
Consumers c1 = new Consumers(pool);
Consumers c2 = new Consumers(pool);
p1.start();
c1.start();
c2.start();
}
} class Pool{
private static int MAX = 1;
private java.util.List<Integer> list = new java.util.LinkedList<Integer>(); public void addList(int i){
synchronized(this){ // 如果 这里以 list 为锁,那么后面的wait notify,notifyAll 都要用 list.wait list.notify list.notifyAll
while (list.size()>=MAX){
try{
this.wait(3);//等待 3 毫秒,然后开始抢所得控制权//防止死锁的方式 一
}
catch (Exception e){ }
}
list.add(new Integer(i));
System.out.println("aft add--->>> "+list.size());
// this.notify(); //如果 采用的是notify,且 wait没有指定参数,那么会形成死锁
this.notifyAll(); //将线程等待序列中的所有等待线程都唤醒,notify 是随机唤醒一个。//防止死锁的方式二
}
} public int remove(){
synchronized(this){
while (list.size()<=0){
try{
wait(3);//这里默认就是用的this.wait
}
catch(Exception e){ }
}
int n = list.remove(0); System.out.println("aft remove______--->>> "+list.size());
notifyAll();
return n;
}
} } class Productors extends Thread{
private String name;
private Pool pool;
static int i = 1; public Productors(Pool pool){
this.pool = pool;
}
public void run(){
while(true){
pool.addList(i);
// System.out.println("p.add--->>> "+);
i ++; }
}
}
class Consumers extends Thread{
private Pool pool;
private String name;
public Consumers(Pool pool){
this.pool = pool;
}
public void run(){
while(true){
int result = pool.remove();
// System.out.println("c.remove --->>> "+result);
}
}
}