你好,我有問題了解這裏提供的代碼,這段代碼展示了一個如何正確實現wait()和notify()到線程的例子。在這些線程中,這個布爾值用於什麼?
下面的代碼:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
我也很難理解這裏的布爾的使用情況,如果布爾變量撐地,該代碼將正確打印。
但是,如果我拿走布爾值,那麼它只會打印「按Control-C停止」。這是爲什麼?
爲什麼布爾這麼重要,它的用法是什麼?
謝謝。