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;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值