我有这种生产者消费者的情况,我正在使用 arrayblockingqueue。如果消费者线程遇到异常,如何停止生产者线程。我需要生产者停止等待队列为空。我引发了强制运行时异常。但程序并没有退出。生产者一直等待队列为空。有人可以帮忙吗
public class ServiceClass implements Runnable{
private final static BlockingQueue<Integer> processQueue = new ArrayBlockingQueue<>(10);
private static final int CONSUMER_COUNT = 1;
private boolean isConsumerInterrupted = false;
private boolean isConsumer = false;
private static boolean producerIsDone = false;
public ServiceClass(boolean consumer,boolean isConsumerInterrupted) {
this.isConsumer = consumer;
this.isConsumerInterrupted = isConsumerInterrupted;
}
public static void main(String[] args) {
long startTime = System.nanoTime();
ExecutorService producerPool = Executors.newFixedThreadPool(1);
producerPool.submit(new ServiceClass(false,false)); // run method is
// called
// create a pool of consumer threads to parse the lines read
ExecutorService consumerPool = Executors.newFixedThreadPool(CONSUMER_COUNT);
for (int i = 0; i < CONSUMER_COUNT; i++) {
consumerPool.submit(new ServiceClass(true,false)); // run method is
// called
}
producerPool.shutdown();
consumerPool.shutdown();
while (!producerPool.isTerminated() && !consumerPool.isTerminated()) {
}
long endTime = System.nanoTime();
long elapsedTimeInMillis = TimeUnit.MILLISECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
System.out.println("Total elapsed time: " + elapsedTimeInMillis + " ms");
}
@Override
public void run() {
if (isConsumer) {
consume();
} else {
readFile(); //produce data by reading a file
}
}
慕妹3242003
相关分类