我必须使用多线程编写这个生产消费者应用程序。我写了下面的java代码,但无法找出哪里出错了。我还想知道我的类设计是否合适或者我的编码风格是否合适。
提前致谢!!!
编辑
我已经修改了生产消费者代码:但仍然存在一些问题。
import java.util.*;
import java.lang.Thread;
public class pc_example {
public static void main (String [] args) {
Store store = new Store( 10 );
produce p = new produce(store);
consume c = new consume (store);
p.start();
c.start();
}
}
class Store {
public Queue<Integer> Q;
public int max_capacity;
Store( int max_capacity ) {
Q = new LinkedList<Integer>();
this.max_capacity = max_capacity;
}
}
class produce extends Thread {
private Store store;
private int element;
produce ( Store store ) {
this.store = store;
this.element = 0;
}
public void put() {
synchronized (store) {
if (store.Q.size() > store.max_capacity) {
try {
wait();
} catch (InterruptedException e) {}
}
else {
element ++;
System.out.println( "Producer put: " + element );
store.Q.add(element);
notify();
}
}
}
}
class consume extends Thread {
private int cons;
private Store store;
consume (Store store) {
this.store = store;
this.cons = 0;
}
public void get() {
synchronized (store) {
if (store.Q.size() == 0) {
try {
wait();
} catch (InterruptedException e) {}
}
else {
int a = store.Q.remove();
System.out.println( "Consumer put: " + a );
cons++;
if (store.Q.size() < store.max_capacity)
notify();
}
}
}
}
最佳答案
您正在创建两个 Producer_Consumer
实例,它们拥有自己的队列,因此它们之间不存在共享。您不应该在类中实例化队列,而应将其作为构造函数参数提供给外部。
class Producer_Consumer extends Thread {
private final Queue<Integer> queue;
Producer_Consumer(int mode, Queue<Integer> queue)
{
this.queue = queue;
}
public static void main(String[] args)
{
Queue<Integer> queue = new LinkedQueue<Integer>();
Producer_Consumer produce = new Producer_Consumer(queue, 2);
Producer_Consumer consume = new Producer_Consumer(queue, 1);
produce.start();
consume.start();
}
}
可以按照建议使用 java.util.concurrent 包中的阻塞队列来完成进一步的改进。对于此类任务,确实不需要使用 Object
的方法 wait()
和 notify()
。
关于java - 线程锁和条件变量,生产者消费者示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6382633/