我已经实现了生产者和消费者的经典示例。在这里,生产者将在生产value = 0
后休眠 10秒 [由于队列大小小于10,因此不会等待状态]。消费者将消费value =0
,并通知生产者将睡眠一秒钟。
所以我的问题是,为什么消费者通知不中断生产者线程并打印Producer Exception cached
。
以下程序的输出如下:
Producer add value=0
Consumer consumes value=0
(等待10秒)
Producer add value=1
Consumer consumes value=1
(等待10秒)
Producer add value=2
Consumer consumes value=2
生产者和消费者的经典例子。
public class ClassicalProducerConsumer{
public static void main(String[] args) {
Buffer buffer = new Buffer(3);
Thread producer = new Thread(new Runnable() {
@Override
public void run() {
try {
int value = 0;
while (true) {
buffer.add(value);
value++;
Thread.sleep(10000); // Make producer wait for 10 seconds.
}
}catch (Exception ex){
System.out.println("Producer Exception cached");
ex.printStackTrace();
}
}
});
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
int value = buffer.poll();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Consumer Exception cached");
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
class Buffer{
Queue<Integer> queue;
int size;
public Buffer(int size) {
this.size = size;
queue = new LinkedList<>();
}
public void add(int value) throws InterruptedException {
synchronized (this){
while (queue.size() >=size){
wait();
}
System.out.println("Producer add value="+ value);
queue.add(value);
notify();
}
}
public int poll() throws InterruptedException {
synchronized (this){
while (queue.size()==0){
wait();
}
int value = queue.poll();
System.out.println("Consumer consumes value="+ value);
notify();
return value;
}
}
}
答案 0 :(得分:0)
正如@RealSkeptic提到的notify()
与中断无关。在要中断的线程上调用interrupt()
。然后,该线程中的任何阻塞方法都将通过抛出 Interrupted exception (中断异常)来返回控制权。建议通过在catch块中调用Thread.currentThread().interrupt()
来恢复线程的中断状态。