虽然我确实了解线程间通信的要点以及在监视器上使用等待和通知以确保同步 Put/Get 操作 - 我试图理解为什么我们需要下面代码中的Thread.sleep()当我们有一个有效的等待/通知机制时,生产者和消费者?如果我删除了 thread.sleep() - 输出会下地狱!
import java.io.*;
import java.util.*;
public class Test {
public static void main(String argv[]) throws Throwable {
Holder h = new Holder();
Thread p = new Thread(new Producer(h), "Producer");
Thread c = new Thread(new Consumer(h), "Consumer");
p.start();
c.start();
}
}
class Holder {
int a;
volatile boolean hasPut;
public synchronized void put(int i) {
while (hasPut) {
try {
System.out.println("The thread " + Thread.currentThread().getName() + " Going ta sleep...");
wait(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
this.a = i;
hasPut = true;
notifyAll();
}
public synchronized int get() {
while (!hasPut) {
try {
System.out.println("The thread " + Thread.currentThread().getName() + " Going ta sleep...");
wait(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
hasPut = false;
notifyAll();
return this.a;
}
}
class Producer implements Runnable {
Holder h;
public Producer(Holder h) {
this.h = h;
}
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("Putting : "+i);
h.put(i);
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
}
}
}
}
class Consumer implements Runnable {
Holder h;
public Consumer(Holder h) {
this.h = h;
}
public void run() {
for (int i = 0; i < 1000; i++) {
int k = h.get();
System.out.println("Getting : "+k);
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
}
}
}
}