我需要實現一個消費者生產者示例。這是一個簡單的程序,我修改了一下,但我不確定是否存在潛在的問題。如果有人能幫我完善它,我將不勝感激。我現在主要的 問題是,當製片人完成時,我不知道如何阻止消費者。如何根據生產者線程狀態停止消費者線程
我曾嘗試下面的代碼,但停止()已被棄用,這也不起作用:
if (!producer.isAlive()) {
consumer.stop();
}
ProducerConsumer.java:
import java.util.Vector;
public class ProducerConsumer {
public static void main(String[] args) {
int size = 5;
Vector<Integer> sQ = new Vector<Integer>(size);
Thread consumer = new Thread(new Consumer(sQ, size));
Thread producer = new Thread(new Producer(sQ, size));
consumer.start();
producer.start();
if (!producer.isAlive()) {
consumer.stop();
}
}
}
class Consumer implements Runnable {
Vector<Integer> sQ = new Vector<Integer>();
int size;
public Consumer(Vector<Integer> sQ, int size) {
this.sQ = sQ;
this.size = size;
}
@Override
public void run() {
while (true) {
try {
System.out.println("Consuming element: " + consume());;
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int consume() throws InterruptedException {
synchronized (sQ) {
while (sQ.isEmpty()) {
System.out.println("The queue is empty and "
+ Thread.currentThread().getName() + " has to wait."
+ "size is: " + sQ.size());
sQ.wait();
}
sQ.notifyAll();
return sQ.remove(0);
}
}
}
class Producer implements Runnable {
Vector<Integer> sQ = new Vector<Integer>();
int size;
public Producer(Vector<Integer> sQ, int size) {
this.sQ = sQ;
this.size = size;
}
@Override
public void run() {
for (int i = 0; i < 12; ++i) {
try {
produce(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void produce(int i) throws InterruptedException {
synchronized (sQ) {
while (sQ.size() == size) {
System.out.println("The queue is full and "
+ Thread.currentThread().getName() + " has to wait."
+ "size is: " + sQ.size());
sQ.wait();
}
sQ.add(i);
sQ.notify();
}
}
}
將它改爲while(!finished ||!sQ.isEmpty())。你知道我在哪裏可以找到使用Executor的很好的示例/模式嗎? – Flethuseo