First stage Understanding (2017-7-27):
Java places the Wait (), notify (), Notifyall () methods on the object, which means that any object can call this method, which is a reference to "any object has a built-in lock that can be used for thread synchronization." Therefore, when a thread wants to free up the CPU contention and put itself into a wait state, it calls the Wait () method on a lock (object), which is the Notify () or notify () method that lets the current thread wait for another thread to invoke the lock. Synchronization locks are implemented between threads to enable wait-and-wake collaboration. Simple example:
1 Packagecom.lyyc.thread.sample;2 3 4 Importorg.junit.Test;5 6 Public classThreadstatesample {7 8 @Test9 Public voidTest ()throwsException {Ten intthreadcount=10; OneAction action=NewAction (); AThread[] Actions=NewThread[threadcount]; - for(inti=0;i<threadcount;i++){ -actions[i]=NewThread (action); the Actions[i].start (); - } - - while(true){ + for(Thread t:actions) { -System.out.println (T.getname () + ":" +t.getstate ()); + } AThread.Sleep (2000); at synchronized(Action.getlock ()) {//The Wait ()/notify ()/notifyall () method that first obtains a sync lock to invoke the lock -Action.getlock (). Notifyall ();//call Notifyall () on the lock object, comrade other threads enter runnable State - } - } - - } in } - to classActionImplementsrunnable{ + - PublicObject lock=NewObject (); the PublicObject Getlock () { * returnlock; $ } Panax Notoginseng @Override - Public voidrun () { the Try { + synchronized(lock) { AThread.Sleep (2000); the lock.wait (); + } -}Catch(interruptedexception e) { $ //TODO auto-generated Catch block $ e.printstacktrace (); - } - } the - }Wuyi
The Wait (), notify (), Notifyall () method on the Java object object understands