[英]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.