62,621
社区成员
发帖
与我相关
我的任务
分享/*5个生产者,1个篮子,3个消费者;
其中每个生产者一次能生产20个产品,并将产品放入篮子;
篮子总共能放5个产品;
消费者每次从篮子顶端取出产品消费;*/
public class ProducterConsumer
{
public static void main(String[] args)
{
SyncStack ss = new SyncStack();
Producer p1 = new Producer(ss);
Producer p2 = new Producer(ss);
Producer p3 = new Producer(ss);
Producer p4 = new Producer(ss);
Producer p5 = new Producer(ss);
Consumer c1 = new Consumer(ss);
Consumer c2 = new Consumer(ss);
Consumer c3 = new Consumer(ss);
new Thread(p1).start();
new Thread(p2).start();
new Thread(p3).start();
new Thread(p4).start();
new Thread(p5).start();
new Thread(c1).start();
new Thread(c2).start();
new Thread(c3).start();
}
}
class ChanPin
{
public static int counter = 0;
private int id;
public ChanPin()
{
this.id = counter++;
}
public String toString()
{
return "产品" + id;
}
}
//篮子
class SyncStack
{
int index = 0;
ChanPin[] arrCP = new ChanPin[5];
public synchronized ChanPin push(ChanPin cp)
{
while(index == arrCP.length)
{
System.out.println("篮子满了");
try
{
//pop();
this.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
this.notifyAll();//让所有的线程从wait中恢复过来,继续执行后面的语句
System.out.println("??????"+cp);
arrCP[index] = cp;
index++;
System.out.println("生产一个产品,篮子里有+++++>" + index + "个");
return cp;
}
public synchronized ChanPin pop()
{
while(index == 0)
{
System.out.println("篮子空了");
try
{
System.out.println("index "+index);
this.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
this.notifyAll();
index--;
System.out.println("消费一个产品,篮子里有----->" + index + "个");
return arrCP[index];
}
}
//生产者
class Producer implements Runnable
{
SyncStack ss = null;
Producer(SyncStack ss)
{
this.ss = ss;
}
public void run()
{
for(int i=0; i<20; i++)
{
ChanPin cp = new ChanPin();
ss.push(cp);
try
{
Thread.sleep((int)(Math.random()*10));
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
//消费者
class Consumer implements Runnable
{
SyncStack ss = null;
Consumer(SyncStack ss)
{
this.ss = ss;
}
public void run()
{
for(int i=0; i<20; i++)
{
ss.pop();
try
{
Thread.sleep((int)(Math.random()*10));
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c1);
Thread t3 = new Thread(c1);
t1.setDaemon(true);
t2.setDaemon(true);
t3.setDaemon(true);
t1.start();
t2.start();
t3.start();