synchronized(xxx){...};请教者关于这段程序中syncronized代码块及wait的理解
class ThreadA
{
public static void main(String[] args)
{
ThreadB b=new ThreadB();
b.start();
System.out.println("b is start....");
synchronized(b)
{
try
{
System.out.println("Waiting for b to complete...");
b.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()
{
synchronized(this)
{
System.out.println("ThreadB is running..");
for (int i=0;i<5;i++ )
{
total +=i;
System.out.println("total is "+total);
}
notify();
}
}
}
===================================================
打印结果是:
b is start....
Waiting for b to complete...
ThreadB is running..
total is 0
total is 1
total is 3
total is 6
total is 10
Completed.Now back to main thread
Total is :10
===============================================
我不太明白这个打印结果的顺序。
为什么在ThreadA中执行b.wait();之后,ThreadB就开始执行了?
以及为什么ThreadA可以进入synchronized(b)得代码块?ThreadA是依据什么来证明自己已经取得b资源了?
还有就是在ThreadA线程中为什么可以执行b.wait();?到底是让谁wait?
谢谢大家!