java - 线程锁和条件变量,生产者消费者示例

标签 java multithreading

我必须使用多线程编写这个生产消费者应用程序。我写了下面的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/

相关文章:

java - 对类实例的静态引用的性能/处理

java - 均匀交叉比单点交叉产生更差的结果?

multithreading - java 8中javaw进程的私有(private)字节增加

c# - 使用线程池时如何判断线程何时完成?

java - 将变量添加到 android list 文件

java - 更新 SQLite 数据库列行中的值

java - 使用 JNI 检索 jint 值时的随机值

java - Thread.currentThread() 在多核/多处理器系统上的语义?

c# - 异步快速路径

c# - 如何对多线程场景中只执行一次的代码进行单元测试?