该文分别以栈和队列作为存储物品的仓库,生产物品以随机生产26个字母作为替代。以下是具体实现
(1)仓库接口
public interface Depository {
public void producer(Character c);
public Character consumer();
}
(2)以栈作为仓库
public class SynStack implements Depository {
private static final int LENGTH = 6;
private Stack<Character> data;
public SynStack() {
data = new Stack<Character>();
}
@Override
public synchronized void producer(Character c) {
if (data.size() == LENGTH) {
try {
System.out.println("仓库已满");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
data.push(c);
System.out.println("Producer:" + c);
}
@Override
public synchronized Character consumer() {
if (data.size() == 0) {
try {
System.out.println("仓库已空");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
Character result = data.pop();
System.out.println("Consumser:" + result);
return result;
}
}
(3)以队列作为仓库
public class SynQueue implements Depository {
private static final int LENGTH = 6;
private LinkedList<Character> queue;
public SynQueue() {
queue = new LinkedList<Character>();
}
@Override
public synchronized void producer(Character c) {
if (queue.size() == LENGTH) {
try {
System.out.println("仓库已满");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
queue.add(c);
System.out.println("Producer:" + c);
}
@Override
public synchronized Character consumer() {
if (queue.size() == 0) {
try {
System.out.println("仓库已空");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
Character result = queue.removeFirst();
System.out.println("Consumer:" + result);
return result;
}
}
(4)生产者线程
public class Producer implements Runnable {
private Depository depository;
public Producer(Depository de) {
depository = de;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
char c = (char) (Math.random() * 26 + 'A');
depository.producer(c);
try {
Thread.sleep((long) (Math.random() * 300));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
(5)消费者线程
public class Consumer implements Runnable {
private Depository depository;
public Consumer(Depository de) {
depository = de;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
depository.consumer();
try {
Thread.sleep((long) (Math.random() * 800));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
(6)测设类
public class ProducerConsumerTest {
public static void main(String[] args) {
// Depository depository = new SynStack();//测试以栈为仓库
Depository depository = new SynQueue();// 测试以队列为仓库
Runnable pRunnable = new Producer(depository);
Runnable cRunnable = new Consumer(depository);
Thread pThread = new Thread(pRunnable);
Thread cThread = new Thread(cRunnable);
pThread.start();
cThread.start();
}
}