【发布时间】:2025-11-30 09:10:01
【问题描述】:
class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
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() {
synchronized (this) {
for (int i = 0; i < 100; i++) {
total += i;
}
notify();
}
}}
我无法理解上述程序中的代码流程以及如何调用 run 方法。
当对象属于ThreadB 类时,为什么ThreadA 的main() 线程能够同步对象b。除此之外,当main() 线程遇到wait() 时,执行如何转移到ThreadB 中的run()。
【问题讨论】:
标签: java multithreading synchronization runnable