生产者消费者问题

package ss;

import java.util.ArrayList;
import java.util.List;

class MyStack{
private List l=new ArrayList();
synchronized public void push(){
try{
synchronized(l){
if(l.size()==1){
this.wait();
}
l.add("anything "+Math.random());
this.notify();
System.out.println("push="+l.size());
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
synchronized public String pop(){
String returnValue="";
try{
if(l.size()==0){
System.out.println("pop:"+Thread.currentThread().getName()+" thread wait");
this.wait();
}
returnValue=""+l.get(0);
l.remove(0);
this.notify();
System.out.println("after pop :l.size="+l.size());
}catch(InterruptedException e){
e.printStackTrace();
}
return returnValue;

}

}
class P{
private MyStack s;
public P(MyStack s){
super();
this.s=s;
}
public void Ppush(){
s.push();
}
}
class C{
private MyStack s;
public C(MyStack s){
this.s=s;
}
public void Cpop(){
System.out.println("s.pop ="+s.pop());
}
}
class ThreadA extends Thread{
private P p;
public ThreadA(P p){
super();
this.p=p;
}
public void run(){
super.run();
while(true){
p.Ppush();
}
}
}
class ThreadB extends Thread{
private C c;
public ThreadB(C c){
this.c=c;
}
public void run(){
super.run();
while(true){
c.Cpop();
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyStack s=new MyStack();
P p=new P(s);
C c=new C(s);
ThreadA a=new ThreadA(p);
ThreadB b=new ThreadB(c);
a.start();
b.start();
}
}

//结果:

push=1
after pop :l.size=0
s.pop =anything 0.3926486676222882
push=1
after pop :l.size=0
s.pop =anything 0.6808526034066181
push=1
after pop :l.size=0
s.pop =anything 0.31220055066469554
push=1
after pop :l.size=0
s.pop =anything 0.36271743799542533

posted @ 2016-05-03 19:31  马云12314  阅读(71)  评论(0)    收藏  举报