我正在练习这个着名的应用程序,并有一个问题。我发现这个主题在这个主题上有4000个Q / A,但没有一个与这一点有关,因此提出了这个问题。
这是简单的代码 -
class Resource {
int contents;
boolean available = false;
}
class Producer implements Runnable {
Thread t;
private Resource resource;
public Producer(Resource c) {
resource = c;
t=new Thread(this);
t.start();
}
public void run() {
for (int i = 0; i < 3; i++) {
synchronized (resource) {
while (resource.available == true) {
//System.out.println("Producer -> calling wait");
try {
LINE 1 resource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
LINE 2 resource.contents = i;
resource.available = true;
//System.out.println("Producer -> calling notify");
resource.notify();
System.out.println("Producer " + " put: " + resource.contents);
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
}
class Consumer implements Runnable {
Thread t;
private Resource resource;
public Consumer(Resource c) {
resource= c;
t=new Thread(this);
t.start();
}
public void run() {
for (int i = 0; i < 3; i++) {
synchronized (resource) {
while (resource.available == false) {
System.out.println("Consumer -> calling wait");
try {
LINE 3 resource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
LINE 4 resource.available = false;
//System.out.println("Consumer -> calling notify");
resource.notify();
System.out.println("Consumer " + " got: " + resource.contents);
}
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Resource c = new Resource ();
Producer p1 = new Producer(c);
Consumer c1 = new Consumer(c);
}
}
这是输出 -
#1 Producer put: 0
#2 Consumer got: 0
#3 Consumer -> calling wait
#4 Producer put: 1
#5 Consumer got: 1
#6 Consumer -> calling wait
#7 Producer put: 2
#8 Consumer got: 2
所以这是代码流 -
#1 Since available=false, Producer will go to LINE 2, make available=true and notify the other thread.
#2 Since available=true, Consumer will go to LINE 4, make available=false and notify the other thread.
#3 So now code should go back to the Producer thread. But why Consumer is entering it's own wait() block at LINE 3?
我错过了一些简单的东西吗?你能解释一下吗?
许多人提前感谢。
答案 0 :(得分:1)
你问了
3所以现在代码应该回到Producer线程。但为何消费者 在LINE 3进入它自己的wait()块?
好的消费者线程在发出available=false
后会继续运行并通知另一个线程。直到生产者线程不可用= true它将调用wait和blocked。
实施生产者/消费者模式的最佳方式是BlockingQueue
以下是example
答案 1 :(得分:0)
我不知道你的线程是如何协调他们的活动的。当制作人正在睡觉时,它不会等待资源。当Consumer调用resource.notify()时,可能没有Producer在等待资源。
正如@ M Sach已经指出的那样,Consumer线程可以自由继续处理。
此时两个线程没有通过资源相互协调,因此观察到的行为似乎与正在运行的Consumer和睡眠生产者一样。