java wait()方法的使用疑问
代码如下所示,如果让线程b等待--b.wait();输出:Total is: 45;但如果把b.wait()这行注释了,可能输出Total is: 0;这个weit()到底起到了什么作用?
public 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 (Exception e) {
e.printStackTrace();
}
}
System.out.println("Total is: " + b.total);
}
}
class ThreadB extends Thread {
int total;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
total += i;
}
}
}