【发布时间】:2013-07-24 07:20:33
【问题描述】:
我很难理解将wait() 放入Object 类背后的概念。对于这个问题,请考虑 wait() 和 notifyAll() 是否在 Thread 类中。
class Reader extends Thread {
Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public void run() {
synchronized(c) { //line 9
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + c.total);
}
}
public static void main(String [] args) {
Calculator calculator = new Calculator();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
calculator.start();
}
}
class Calculator extends Thread {
int total;
public void run() {
synchronized(this) { //Line 31
for(int i=0;i<100;i++) {
total += i;
}
notifyAll();
}
}
}
我的问题是它可以带来什么不同?在第 9 行中,我们正在获取对象 c 上的锁,然后执行等待,它满足等待条件,即我们需要在使用 wait 之前获取对象上的锁,因此在第 31 行获得了对 Calculator 对象的锁的 notifyAll 的情况.
【问题讨论】:
-
很难理解你在问什么......
-
我在问我们是否在 Thread 类中放置了等待和通知,然后我认为这段代码可能有效。
-
.wait()和.notify{,All}()位于Object,而不是Thread。这就是允许在 JVM 中实现许多锁定原语的原因(Semaphore、CountDownLatch等) -
这段代码并不真正适用于这个问题,因为
Thread是Object的子类,就像其他所有东西一样。您永远不会尝试在非Thread对象上调用wait(),因此代码与您的问题无关。
标签: java multithreading wait notify