简单的生产者与消费者的代码demo
详细看代码,代码中有注释
public class ProduceConsume{
//生产者消费者例子
private StackSteamBread ssb=new StackSteamBread();
private Produce p=new Produce(ssb);
private Consume c=new Consume(ssb);
public void myrun() {
Thread tp=new Thread(p);
tp.start();
Thread tc=new Thread(c);
tc.start();
}
public static void main(String[] args) {
ProduceConsume pr=new ProduceConsume();
pr.myrun();
}
}
//馒头类
class SteameBread {
private int id;
public SteameBread(int id) {
this.id=id;
}
@Override
public String toString() {
return "馒头:"+id;
}
}
//馒头框类,类似于栈
class StackSteamBread {
private int index=0;
private SteameBread [] sb=new SteameBread[6];
//涉及到多个线程使用同一资源,则想到使用snychronized
public synchronized void push(SteameBread sbread) {
if(index==sb.length) {
try {
this.wait();
System.out.println("装满了,请等下生产");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//每次唤醒一下
this.notify();
sb[index]=sbread;
System.out.println("生产 "+sbread);
index++;
}
//拿出馒头,从最上面的开始拿,遵守栈的先进后出,后进先出
public synchronized SteameBread pop() {
if(index==0) {
try {
this.wait();
System.out.println("没有馒头了");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
index--;
System.out.println("消费 "+sb[index]);
return sb[index];
}
}
//生产者
class Produce implements Runnable{
private StackSteamBread ssb=null;
public Produce(StackSteamBread ssb) {
this.ssb=ssb;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
SteameBread sbread=new SteameBread(i+1);
ssb.push(sbread);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consume implements Runnable{
private StackSteamBread ssb=null;
public Consume(StackSteamBread ssb) {
this.ssb=ssb;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
SteameBread s=ssb.pop();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}