1.
1 Public classLISTADD1 {2 Private volatile StaticList List =NewArrayList ();3 4 Public voidAdd () {5List.add ("Hello");6 }7 8 Public intsize () {9 returnlist.size ();Ten } One A Public Static voidMain (string[] args) { - FinalListAdd1 List1 =NewListAdd1 (); - FinalObject lock =NewObject (); theThread T1 =NewThread (NewRunnable () { - @Override - Public voidrun () { - synchronized(lock) {//Object Lock + Try { - for(inti = 0; I < 10; i++) { + List1.add (); ASystem.out.println (Thread.CurrentThread (). GetName () + "added an element ..."); atThread.Sleep (100); - - if(list1.size () = = 5) { -SYSTEM.OUT.PRINTLN ("Issue wake-up notification ..."); -Lock.notify ();//The current thread continues execution without releasing lock lock for the current thread - } in } -}Catch(Exception e) { to e.printstacktrace (); + } - } the * } $}, "T1");Panax Notoginseng -Thread t2 =NewThread (NewRunnable () { the @Override + Public voidrun () { A synchronized(lock) {//Object Lock the if(List1.size ()! = 5){ + Try { -Lock.wait ();//Release Lock $}Catch(interruptedexception e) { $ e.printstacktrace (); - } -System.out.println (Thread.CurrentThread (). GetName () + "Thread Stop"); the Throw Newruntimeexception (); - }Wuyi } the } -}, "T2"); Wu -T2.start ();//First T2 monitoring, not equal to release the lock, was T1 get, T1 add to 5 notice, continue to wait until execution, T2 start execution! About T1.start (); $ - /*T1 added an element ... - T1 added an element ... - T1 added an element ... A T1 added an element ... + T1 added an element ... the issue wake-up notification : - T1 added an element ... $ T1 added an element ... the T1 added an element ... the T1 added an element ... the T1 added an element ... the T2 Thread Stop - Exception in thread "T2" Java.lang.RuntimeException in At Com.bjsxt.base.thread06.listadd1$2.run (listadd1.java:54) the At Java.lang.Thread.run (thread.java:744)*/ the } About}
View Code
Multithreading 9---Non-real-time communication between threads--lock's wait and notify