/**
*
* 生成者消费者问题
**/
public class ThreadDemo2{
public static void main(String args[])
{
BufferData bd = new BufferData();
Producer pro = new Producer(bd,"填装者1");
Producer pro2 = new Producer(bd,"填装者2");
Producer pro3 = new Producer(bd,"填装者3");
Consumer con = new Consumer(bd);
new Thread(pro).start();
new Thread(pro2).start();
new Thread(pro3).start();
new Thread(con).start();
}
}
//生产者
class Producer implements Runnable{
private BufferData bd;
private String name;
public Producer(BufferData bd,String name)
{
this.bd = bd;
this.name = name;
}
public void run()
{
int count = 10000;
while(count >0){
bd.setData(1, name);
count--;
}
}
}
//消费者
class Consumer implements Runnable
{
private BufferData bd;
public Consumer(BufferData bd){
this.bd = bd;
}
public void run()
{
int count = 10000;
while (count>0)
{
bd.getData(1, "");
//System.out.println(bd.toString());
count--;
//bd.notifyAll();
}
}
}
class BufferData{
private int id = 0;
private String name="";
private boolean isFull = false;
//填装子弹
public synchronized void setData(int n, String name)
{
try
{
if (isFull)
{
this.wait();
}
this.id += n;
this.name = name;
if(this.id == 10){ isFull = true; this.notifyAll();}
System.out.println(this.name+":"+"装子弹------------"+this.id+",isFull="+isFull);
Thread.sleep(500);
}
catch (Exception e)
{
e.printStackTrace();
}
}
//打枪
public synchronized void getData(int n, String name)
{
try
{
if (!isFull)
{
//System.out.println("正在填装......");
this.wait();
}
}
catch (Exception e)
{
e.printStackTrace();
}
id = id-n;
if(id<=0)
{
this.isFull = false;
this.notifyAll();
}
System.out.println("剩余子弹------------"+id+",isFull="+isFull);
}
public String toString(){
return "id=" + id + " name=" + name;
}
}