`

ProductAndConsumer

阅读更多
package multithreading;



public class ProductConsumer {
public static void main(String[] args)
{
	Stack stack=new Stack("s1");
	Productor p1=new Productor("p1",stack);
	Consumer c1=new Consumer("c1",stack);
}
}

class Consumer extends Thread
{
    private Stack stack;
    public Consumer(String name,Stack s){super(name);this.stack=s;start();}
    public void run()
    {
    	String goods;
    	for(int i=0;i<10;i++)
    {
    	goods=stack.pop();
    	System.out.println(getName()+" pop "+goods+"from "+stack.getName());
    	yield();
    }
}
}
    
class Productor extends Thread
{
	private Stack stack;
	public Productor(String name,Stack s){super(name);this.stack=s;start();}
	public void run()
	{
		String goods;
		for(int i=0;i<10;i++)
		synchronized(stack){
		goods="goods"+(stack.getPoint()+1);
		stack.push(goods);
		System.out.println(getName()+":push "+goods+" to "+stack.getName());
	
	   }
	}
	
}


class Stack
{
private String name;
private String[] buffer=new  String[100];
int point=-1;
public Stack(String name){this.name=name;}
public String getName()
{
	return this.name;
}
//get the top goods and remove it
public synchronized String pop()
{
	String goods=buffer[point];
	buffer[point]=null;
	Thread.yield();
	point--;
	return goods;
}
//push goods into stack	
public synchronized void push(String goods)
{
	point++;
	Thread.yield();
	buffer[point]=goods;
	
}
public synchronized int getPoint()
{
	return this.point;
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics