The procedure is as follows:
Public static void main (String[] args) throws Exception{ final list list = new arraylist (); final object lock = new object (); thread t1 = new thread ( New runnable () { @Override public void run () { synchronized (Lock) { for (int i = 0 ; i < 10 ; i + +) { list.add (i); if (List.size () == 5) { lock.notify (); system.out.println (Thread.CurrentThread (). GetName () + "give notice!"); } } } system.out.println (Thread.CurrentThread (). GetName () + "execute over! "); } }); thread t2 = new&nbSp Thread (new runnable () { @Override public void run () { synchronized (Lock) { if (List.size () != 5) { try { lock.wait (); } catch (interruptedexception e) { &nbSp;e.printstacktrace (); } } system.out.println (Thread.CurrentThread (). GetName () + " receive notification!"); } system.out.println (Thread.CurrentThread (). GetName () + "execute over! "); } }); t2.start () ; thread.sleep (+); t1.start ();}
Analysis:
The intention of the program is to use the communication between multithreading, using wait/notify implementation, but the result of the operation is that although the thread T1 issued a notification, but the thread T2 did not immediately receive notification to execute, this is why? because only the thread T1 execution has released the lock, T2 can execute, that is, wait/notify is not real-time (wait to release the lock, and notify does not release the lock caused ), then the real-time communication between the threads what to do? Can be achieved using Countdownlatch.
Improvements to the program:
Public static void main (String[] args) throws Exception{ final list list = new arraylist (); final object lock = new object (); final countdownlatch countdownlatch = new countdownlatch (1); thread t1 = new thread (new runnable () { @Override public void run () { for (int i = 0 ; i < 10 ; i++) { list.add (i); if (List.size () == 5) { Countdownlatch.countdown (); system.out.println (Thread.currentThread (). GetName () + "give notice!"); } } system.out.println ( Thread.CurrentThread (). GetName () + "execute over!"); } }); thread t2 = new thread (new runnable () { @Override public void run () { if (List.size () != 5) { try { Countdownlatch.await (); } catch (interruptedexception e) { e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + " receive notification!"); } system.out.println (Thread.CurrentThread (). GetName () + "execute over! "); } }); t2.start () ; thread.sleep (+); t1.start ();}
This article is from the "Boundless Mind Infinite" blog, please be sure to keep this source http://zhangfengzhe.blog.51cto.com/8855103/1875221
Analysis of a multi-threaded communication case