import java.util.LinkedList;
public class PC{
private static LinkedList<Object> list = new LinkedList<Object>();
private int MAX = 10;
public static void main(String args[]){
PC pc = new PC();
pc.start();
}
public void start(){
Producer p = new Producer("Producer1");
Customer c1 = new Customer("Customer1");
Customer c2 = new Customer("Customer2");
p.start();
c1.start();
c2.start();
}
class Producer extends Thread{
public Producer(String threadName){
super(threadName);
}
Object o = null;
public void run(){
for(int i=1;i<=2;i++){
try{
sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(list){
try{
while(list.size()==MAX){
System.out.println("Warning:list is Full!");
list.wait();
}
o = new Object();
list.add(o);
System.out.println(getName() + ": " + o +"生产第:"+i+"个");
list.notifyAll();
}catch(InterruptedException e){
System.out.println("Producer is interrupted!");
}
}
}
}
}
static class Customer extends Thread{
public static int i = 1;
public Customer(String threadName){
super(threadName);
}
public void run(){
while(i <= 2){
try{
sleep(200);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(list){
try{
while(list.size()==0){
System.out.println("Warning-"+getName()+":list is Empty!");
list.wait();
break;
}
Object o = list.removeLast();
System.out.println(getName() + ": " + o +"消费第:"+(i++)+"个");
list.notifyAll();
}catch(InterruptedException e){
System.out.println("Customer is interrupted!");
}
}
}
}
}
}
//有个消费者线程退不出来, 怎么改一下让他退出来?
生产者只生产两个线程就结束,
而消费者要消费三个才结束。消费者消费完的时候判断没有货物了就在wait生产者生产,就卡死了消费者线程改成i<2就行了
1号消费者消费了一个,然后sleep
2号消费者拿到锁,(这时候生产者应该还没sleep完,所以是2号消费者拿到的),这时候消费者中的i=2
判断没有货物了,所以2号进wait池,锁抛开,这时候消费者中i还是等于2
1号生产者先sleep完,拿到锁生产第二个,生产完线程死亡
1号消费者sleep完,拿到锁消费第二个,消费完i=3,该线程结束
2号消费者拿到锁,这时候因为是while循环,所以它判断没有货物又继续wait了,所以卡死在这里上面把while(i<2)是剥夺了1号消费者第二次消费的权利,这样2号才能成功消费并退出...