我正在練習這個着名的應用程序,並有一個問題。我發現這個網站有4000個關於這個主題的Q/A,但是沒有一個與這個問題有關,因此提出這個問題。JAVA消費者生產者多線程應用程序 - 代碼流程
下面是簡單的代碼 -
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?
我失去了一些東西簡單?你能解釋一下嗎?
很多人提前感謝。
嗨薩克 - 非常感謝答覆。所以重點是消費者線程將繼續運行 - 它將在它的塊內來回遍歷,直到它調用wait(),然後控件將轉到另一個線程。我錯過了這一點。歡呼,從我的盡頭! –
是的,你是對的。 –