package pack;
/*
* author tan
*/
//主类
class ThreadMain
{
public static void main(String[] args)
{
StackBasket s = new StackBasket();
Producer p = new Producer(s);
Consumer1 c1 = new Consumer1(s);
Consumer2 c2 = new Consumer2(s);
Thread tp = new Thread(p);
Thread tc1 = new Thread(c1);
Thread tc2 = new Thread(c2);
tp.start();
tc1.start();
tc2.start();
}
}
//
class Business
{
private int id;
Business(int id){
this.id = id;
}
public String toString(){
return "产品ID :" + id;
}
}
//共享栈空间
class StackBasket
{
Business sm[] = new Business[6];
int index = 0;
public synchronized void push(Business m){
try{
while(index == sm.length){
System.out.println("*********生产满了*********");
this.wait();
}
this.notify();
}catch(InterruptedException e){
e.printStackTrace();
}catch(IllegalMonitorStateException e){
e.printStackTrace();
}
sm[index] = m;
index++;
System.out.println("生产了:" + m + " 共" + index + "个产品");
}
public synchronized Business pop(){
try{
while(index == 0){
System.out.println("*********消费光了*********");
this.wait();
}
this.notify();
}catch(InterruptedException e){
e.printStackTrace();
}catch(IllegalMonitorStateException e){
e.printStackTrace();
}
index--;
System.out.println("1号消费者消费了:————" + sm[index] + " 共" + (index+1) + "个产品");
return sm[index];
}
public synchronized Business pop1(){
try{
while(index == 0){
System.out.println("*********消费光了*********");
this.wait();
}
this.notify();
}catch(InterruptedException e){
e.printStackTrace();
}catch(IllegalMonitorStateException e){
e.printStackTrace();
}
index--;
System.out.println("2号消费者消费了:————" + sm[index] + " 共" + (index+1) + "个产品");
return sm[index];
}
}
class Producer implements Runnable
{
StackBasket ss = new StackBasket();
Producer(StackBasket ss){
this.ss = ss;
}
// 生产进程.
public void run(){
for(int i = 0;i < 20;i++){
Business m = new Business(i);
ss.push(m);
try{
Thread.sleep((int)(Math.random()*500));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//一号消费者
class Consumer1 implements Runnable
{
StackBasket ss = new StackBasket();
Consumer1(StackBasket ss){
this.ss = ss;
}
// 消费进程1.
public void run(){
for(int i = 0;i < 20;i++){
Business m = ss.pop();
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//二号消费者
class Consumer2 implements Runnable
{
StackBasket ss = new StackBasket();
Consumer2(StackBasket ss){
this.ss = ss;
}
// 消费进程2.
public void run(){
for(int i = 0;i < 20;i++){
Business n = ss.pop1();
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}