【发布时间】:2019-10-21 23:25:49
【问题描述】:
我的问题纯粹是概念性的。并且只是为了更深入地了解线程之间的通信。
在生产者消费者问题中,
- 有一个生产者线程和一个消费者线程。
- 生产者线程调用方法produce,消费者线程调用方法consume。
The example code is taken from here
package ProducerConsumer;
import java.util.LinkedList;
import java.util.Queue;
public class ClassicProducerConsumerExample {
public static void main(String[] args) throws InterruptedException {
Buffer buffer = new Buffer(2);
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
buffer.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
buffer.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
producerThread.join();
consumerThread.join();
}
static class Buffer {
private Queue<Integer> list;
private int size;
public Buffer(int size) {
this.list = new LinkedList<>();
this.size = size;
}
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
while (list.size() >= size) {
// wait for the consumer
wait();
}
list.add(value);
System.out.println("Produced " + value);
value++;
// notify the consumer
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (list.size() == 0) {
// wait for the producer
wait();
}
int value = list.poll();
System.out.println("Consume " + value);
// notify the producer
notify();
Thread.sleep(1000);
}
}
}
}
}
我已经读过等待和通知应该在同步块内以避免竞争条件。
我不明白为什么当两个线程都调用不同的方法时,我应该将 wait() 和 notify() 包含在同步块中。消费者线程不会调用生产(),所以如果我不使用同步关键字将等待调用包含在生产方法中,那么它的行为应该仍然相同,因为生产()只被生产者线程调用。对吗?
【问题讨论】:
标签: java multithreading wait synchronized producer-consumer