我使用堆栈作为存储来实现我的生产者-消费者模型。
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Stackable<Integer> stack = new MyArrayStack<Integer>();
Producer producer = new Producer(stack);
Consumer consumer = new Consumer(stack);
producer.start();
consumer.start();
}
private static class Producer extends Thread {
public Producer(Stackable<Integer> s) {
mStack = s;
}
private Stackable<Integer> mStack = null;
private int mNumber = 0;
@Override
public void run() {
// TODO generates number here
while(true){ synchronized(this){
while(!mStack.isEmpty())
{
try{
this.wait();
} catch(Exception e)
{
e.printStackTrace();
}
}
mNumber++;
System.out.println("Producer generates number:" + mNumber);
mStack.push(mNumber);
this.notifyAll();
}
}
}
}
private static class Consumer extends Thread {
public Consumer(Stackable<Integer> s) {
mStack = s;
}
private Stackable<Integer> mStack = null;
@Override
public void run() {
// TODO consume number here.
while(true){
synchronized(this){
while(mStack.isEmpty())
{
try{
this.wait();
} catch(Exception e)
{
e.printStackTrace();
}
}
int number = mStack.pop();
System.out.println("Consumer consumes number:" + number);
this.notifyAll();
}
}}
}
}
但是,当我测试程序时,似乎只有生产者会工作,它会不断生成数字,而消费者线程似乎不工作。
专家可以帮我调试我的代码哪里出错了吗?谢谢。
编辑:我的堆栈代码是: public class MyArrayStack implements Stackable {
private static final int DEFAULT_SIZE = 16;
protected int sp; // empty stack
protected E[] head; // array
private int size;
private int count;
MyArrayStack(int size) {
if (size <= 0)
throw new IllegalArgumentException(
"Stack's capacity must be positive");
head = (E[])new Object[size];
sp = -1;
count=0;
}
public boolean isFull() {
return sp == this.size -1;
}
@Override
public void push(Object e) {
if (!isFull())
{
head[++sp] = (E) e;
count++;
}
}
@Override
public E pick() {
if (sp == -1)
try {
throw new Exception("Stack is empty");
} catch (Exception e) {
e.printStackTrace();
}
return head[sp];
}
@Override
public E pop() {
count--;
if (isEmpty()) {
return null;
} else
return head[sp--];
}
@Override
public int count() {
return count;
}
@Override
public boolean isEmpty() {
return (sp == -1);
}
}