最近在看java并发编程,生产者与消费者是个经典题目,5年前去百度面试的时候,让我当场写出这个程序,今天我就回顾一下,这里涉及到几个点,一个生产者,一个消费者,一个馒头实体类,一个馒头筐类,一个main方法类,记住这几个点,生产者和消费者程序就很好写了,代码如下:
/*
* 生产者与消费者问题
*/
public class ProduceConsume {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Produce pd = new Produce(ss);
Consume cs = new Consume(ss);
Thread t1 = new Thread(pd);
Thread t2 = new Thread(cs);
t1.start();
t2.start();
}
}
/*
* 馒头实体类
*/
class ManTou {
private int id;
public ManTou(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "ManTou " + getId();
}
}
/*
* 馒头框类
*/
class SyncStack {
int index = 0;
ManTou[] mtArray = new ManTou[6];
public synchronized void push(ManTou mt) {
while (index == mtArray.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
mtArray[index] = mt;
index++;
System.out.println("生产了" + mt);
}
public synchronized ManTou pop() {
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
System.out.println("消费了" + mtArray[index]);
return mtArray[index];
}
}
/*
* 生产者
*/
class Produce implements Runnable {
SyncStack ss = null;
public Produce(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
ManTou mt = new ManTou(i);
if (ss != null) {
ss.push(mt);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/*
* 消费者
*/
class Consume implements Runnable {
SyncStack ss = null;
public Consume(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
if (ss != null) {
ss.pop();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
以上代码,凭记忆手工敲的,如有问题,欢迎指正。