class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
System.out.println("b is start....");
synchronized (b)//括号里的b是什么意思,起什么作用,b作为对象锁,是锁住b线程的synchronized中代码还是主线程synchronized中代码? <1>
{
try {
System.out.println("Waiting for b to complete...");
b.wait();//这一句是什么意思,究竟让谁wait?
System.out.println("Completed.Now back to main thread");
} catch (InterruptedException e) {
}
}
System.out.println("Total is :" + b.total);
}
}
class ThreadB extends Thread {
int total;
public void run() {
/* try {
}catch(Exception ex){}*/
synchronized (this) //<2>
{
System.out.println("ThreadB is running..");
for (int i = 0; i < 10; i++) {
total += i;
System.out.println("total is " + total);
}
notify();
}
}
}
...奇怪的描述,..我这里很明显的wait了。。
正常情况下,B和A都是去拿B的对象锁,B先执行的,等B执行完,才会到A,那A会一直wait,没有人去notify它了。。
//这是打印的输出,明显A那后面没输出了啊。。。
//话说这是想测试wait是不是会释放锁吗。。
ThreadB is running..
total is 0
total is 1
total is 3
total is 6
total is 10
total is 15
total is 21
total is 28
total is 36
total is 45
b is start....
Waiting for b to complete...