下面是我原来在CSDN论坛上看到的一个贴子,涉及到同步,wait(),notify()等概念的理解,我试着根据原来的一些回复和Think in java上的相关概念将wait()和notify()这两个方法剖析了一下,欢迎指教.
问题如下:
//分析这段程序,并解释一下,着重讲讲synchronized、wait(),notify 谢谢! class ThreadA { public static void main(String[] args) { ThreadB b=new ThreadB(); b.start(); System.out.PRintln("b is start...."); synchronized(b)//括号里的b是什么意思,起什么作用? { 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() { synchronized(this) { System.out.println("ThreadB is running.."); for (int i=0;i<100;i++ ) { total +=i; System.out.println("total is "+total); } notify(); } } }