【发布时间】:2017-05-25 19:26:55
【问题描述】:
最近学习了Java线程通信中的notify和wait,试着写了Consumer&Producer的经典问题,在我的代码中,我实际上有4个线程,2个是消费者,另外2个是生产者。
package producer_consumer;
class Shared {
private volatile boolean writable = true;
public Character character = 'A';
public synchronized void produceChar(Character c) {
while (!writable) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writable = false;
character = c;
notify();
}
public synchronized void consumerChar() {
while (writable) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writable = true;
notify();
}
}
public class PC {
public static void main(String[] args) {
Shared shared = new Shared();
class Producer extends Thread {
@Override
public synchronized void run() {
for(Character character = 'A';character<'Z';character++) {
shared.produceChar(character);
System.out.println(shared.character + " is produced");
}
}
}
class Consumer extends Thread {
@Override
public synchronized void run() {
do {
shared.consumerChar();
System.out.println(shared.character + " is consumed");
}while (shared.character!='Z');
}
}
Producer p1 = new Producer();
Producer p2 = new Producer();
Consumer c1 = new Consumer();
Consumer c2 = new Consumer();
p1.start();
p2.start();
c1.start();
c2.start();
}
}
但是,当我尝试运行代码时,它没有成功。我以为它会打印从 A 到 Z 的字母,但它总是卡住。我知道一定有什么问题,但我自己无法弄清楚。实际上,我不知道它有什么问题。那么,有人会帮助我吗?谢谢!
【问题讨论】:
-
有时它可以正常工作,但有时不能。打印几个字符后它会停止
-
不要同步你的运行方法。它只被调用一次。
-
你应该使用
notifyAll()而不是notify(),因为有超过1个消费者线程和1个生产者线程
标签: java multithreading wait producer-consumer