When we us java Thread,Sometimes we nedd concurrent visit some resources, in this way,we have to use synchronized.
today what we will talk about is wait and notify.
first have a look at this fragment.
public Class A { public static void main(String[]args) { ThreadB b = new ThreadB(); b.start(); synchronized(b) { System.out.println("waiting......"); b.wait(); } System.out.println("result:"+b.getResult()); } }
------------------------ThreadB-------------------------
public Class ThreadB extends Thread { public void run() { synchronized(this) { ...... notify(); } } }
-----------------------now analyse----------------------
1.When use wait or notify, it must be parceled by synchronized.
reasons are:
1.1 the current thread must has the object's lock.
1.2 then the object can invoke wait() to late the current thread release the lock.
1.3 as the current thread do not has the object'lock,it has to wait until the object notify
2.If ThreadB do not invock notify(),the main thread will keep waiting.
when the thread which need invoke notifyall() method.if the thread is gone, it will notify automaticlly.