[英]JAVA consumer-producer multi-threaded application - flow of code
我正在练习这个著名的应用程序,并且有一个问题。 我发现此站点上有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?
我是否缺少简单的东西? 你能解释一下吗?
非常感谢。
您询问
3现在,代码应返回到Producer线程。 但是,为什么消费者要在第3行输入它自己的wait()块?
好消费者线程将在available=false
后继续运行,并通知另一个线程。 直到生产者线程不可用= true,它将调用wait并被阻止。
实现生产者/消费者模式的最佳方法是通过BlockingQueue
这是例子
我看不到您的线程如何协调其活动。 当生产者在睡觉时,它并不在等待资源。 当使用者调用resource.notify()时,可能没有生产者正在等待资源。
正如@ M Sach已经指出的那样,使用者线程可以自由继续处理。
此时,两个线程尚未通过资源相互协调,因此观察到的行为似乎与运行中的使用者和睡眠中的生产者所期望的一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.