如何在java中停止生产者和消费者问题中的线程? [英] how can I stop a thread in producer and consumer problem in java?
本文介绍了如何在java中停止生产者和消费者问题中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的消费者类
我不知道在产品生产之前我怎么能停止一个线程?
(睡眠似乎不起作用)
请建议我除阻塞队列界面和睡眠方法以外的其他方式
this is my consumer class
I cant know how can I stop a thread until a product will be produced?
(the sleep seems not work sometimes)
please suggest me a way other than the blocking queue interface and sleep method
package producerconsumer;
import java.util.Scanner;
public class Consumer implements Runnable {
Thread t;
String consumerName;
public Consumer(String name) {
t = new Thread(this, name);
t.start();
}
@Override
public void run() {
int m = Producer_consumer.n;
try {
if (m!=0) {
Producer_consumer.delay.acquire();
}
else
{
Thread.sleep(100); //??
}
while (true) {
Producer_consumer.criticalSection.acquire();
consumerName = Thread.currentThread().getName();
consume();
Producer_consumer.n--;
Producer_consumer.form.setLable(Producer_consumer.n + "");
m = Producer_consumer.n;
Producer_consumer.criticalSection.release();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
推荐答案
看起来像你的问题是通过一些其他线程的主动异步停止一个线程(只有这种情况通常会导致困难)。
整个事情是一个有争议的话题,我不想在这里讨论。我说几句,我不喜欢它是如何在Java中完成的。大多数人通过使用某个成员(布尔标志)以协作方式停止线程,该成员可以通过线程轮询来停止并由单独的线程设置。此外,Thread.interrupt
可以使用,但有一些buts。本文对此进行了详细介绍: http://www.javamex.com/tutorials/threads/stopping_thread.shtml [ ^ ]。
请注意,关于生产者 - 消费者模式以及阻塞队列的使用,提到了排队条件的技术。
-SA
It looks like your problem is stopping a thread asynchronously, by the initiative of some other thread (only this situation usually causes difficulties).
The whole thing is a controversial topic I don't want to discuss here. I a few words, I dislike how it's done in Java. Most people stop thread in a collaborative way, by using some member (Boolean "flag") which can polled by a thread to be stopped and set by a separate thread. Also,Thread.interrupt
can be used, with, but with certain "buts". This is pretty well described in this article: http://www.javamex.com/tutorials/threads/stopping_thread.shtml[^].
Note that the technique of "queued condition" is mentioned in relation to the producer-consumer patters and the use of blocking queue.
—SA
这篇关于如何在java中停止生产者和消费者问题中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文