package mypackage;
import java.util.*;
public class iphxer
{
public static void main(String s[])
{
System.out.println("开始生产和消费了!");
M m = new M();
m.start();
}
}
class M extends Thread
{
public int MAX;
public Queue queue = new LinkedList();
public M()
{
this.MAX=10;
}
public void run()
{
produce p = new produce(5000);
p.start();
consumer c = new consumer(1000);
c.start();
}
public boolean isempty()
{
return this.size() == 0;
}
public boolean isfull()
{
return this.MAX <= this.size();
}
public void push_back(String s)
{
this.queue.offer(s);
}
public String pop_front()
{
return this.queue.poll();
}
public int size()
{
return this.queue.size();
}
class produce extends Thread
{
private int num;//生产数量
private int time;//生产速度
public produce(int time)
{
this.time = time;
this.num = 0;
System.out.println("生产者对象已经构造出来了……");
}
public void run()
{
System.out.println("生产者开始生产了!");
while(true)
{
try
{
while(!M.this.isfull())
{
System.out.println("生产第" + (M.this.size() + 1) + "个……总第" + this.num + "个 ");
Thread.sleep(this.time);//表示生产的速度;
M.this.push_back("产品" + M.this.size());
// System.out.println("成功生产第" + (M.this.size() + 1) + "个……");
++this.num;
Thread.sleep(500);
}
}
catch(Exception e)
{
e.setStackTrace(null);
}
System.out.println("生产满了,正在等待……");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
e.setStackTrace(null);
}
}
}
}
class consumer extends Thread
{
private int num;//消费数量
private int time;//消费速度
public consumer(int time)
{
this.time = time;
this.num = 0;
}
public void run()
{
String s;
while(true)
{
while(!M.this.isempty())
{
try
{
System.out.println("消费第" + (M.this.size()) + "个……总第" + (this.num + 1) + "个 ");
Thread.sleep(this.time);//表示生产的速度;
s = M.this.pop_front();
//System.out.println("成功消费" + s + "……");
++this.num;
Thread.sleep(500);
}
catch(Exception e)
{
e.setStackTrace(null);
}
}
System.out.println(" 产品空了,正在等待生产……");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
e.setStackTrace(null);
}
}
}
}
}