我正在准备 SCJP 考试,但无法完全理解同步。在第 6 行,我读到 main 中运行的线程需要锁定“b”。为什么它需要锁定这个对象?我的理解是,同步的代码块是一个保护区,任何时候只有一个线程可以进入?继续前进,main 中的线程释放此锁并等待 'b 中的线程完成其 run 方法。然后,'b' 中的线程用于通知 main 中的线程它已完成。但是,它看起来并没有在这里通知任何特定的线程。这个例子来自 Sierra 和 Bates SCJP 的书。任何可以阐明这一点的光都将不胜感激。谢谢
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
**synchronized(b) { //line 6**
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
System.out.println("K");
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
}