The architect formed a--5. Communication between threads

Source: Internet
Author: User
Tags thread stop volatile

Using wait and notify to communicate between threads, these two methods are object methods that must be used with synchronized. The Wait method releases the lock and notify does not release the lock.

How the original thread communicates

1 Importjava.util.ArrayList;2 Importjava.util.List;3 4  Public classLISTADD1 {5 6     7     Private volatile StaticList List =NewArrayList (); 8     9      Public voidAdd () {TenList.add ("BJSXT"); One     } A      Public intsize () { -         returnlist.size (); -     } the      -      Public Static voidMain (string[] args) { -          -         FinalListAdd1 List1 =NewListAdd1 (); +          -Thread T1 =NewThread (NewRunnable () { + @Override A              Public voidrun () { at                 Try { -                      for(inti = 0; I <10; i++){ - List1.add (); -System.out.println ("Current thread:" + thread.currentthread (). GetName () + "added an element ..."); -Thread.Sleep (500); -                     }     in}Catch(interruptedexception e) { - e.printstacktrace (); to                 } +             } -}, "T1"); the          *Thread t2 =NewThread (NewRunnable () { $ @OverridePanax Notoginseng              Public voidrun () { -                  while(true){ the                     if(list1.size () = = 5){ +System.out.println ("Current thread received notification:" + thread.currentthread (). GetName () + "List size = 5 thread stop ..."); A                         Throw Newruntimeexception (); the                     } +                 } -             } $}, "T2");  $          - T1.start (); - T2.start (); the     } -     Wuyi      the}
View Code

There is a cycle of death, and this is not a good way.

You should replace (with wait) in the following manner, noting the thread boot order:

1 Importjava.util.ArrayList;2 Importjava.util.List;3 ImportJava.util.Queue;4 ImportJava.util.concurrent.CountDownLatch;5 ImportJava.util.concurrent.LinkedBlockingDeque;6 ImportJava.util.concurrent.LinkedBlockingQueue;7 /**8 * Wait Notfiy method, wait release lock, notfiy not release lock9  * @authorAlienwareTen  * One  */ A  Public classLISTADD2 { -     Private volatile StaticList List =NewArrayList ();  -      the      Public voidAdd () { -List.add ("BJSXT"); -     } -      Public intsize () { +         returnlist.size (); -     } +      A      Public Static voidMain (string[] args) { at          -         FinalLISTADD2 List2 =NewListAdd2 (); -          -         //1 instantiation of a lock -         //when using wait and notify, be sure to work with the Synchronized keyword -         //Final Object lock = new Object (); in          -         FinalCountdownlatch Countdownlatch =NewCountdownlatch (1); to          +Thread T1 =NewThread (NewRunnable () { - @Override the              Public voidrun () { *                 Try { $                     //synchronized (lock) {Panax Notoginseng                          for(inti = 0; I <10; i++){ - List2.add (); theSystem.out.println ("Current thread:" + thread.currentthread (). GetName () + "added an element ..."); +Thread.Sleep (500); A                             if(list2.size () = = 5){ theSYSTEM.OUT.PRINTLN ("Notification has been issued ..."); + Countdownlatch.countdown (); -                                 //lock.notify (); $                             } $                         }                         -                     //} -}Catch(interruptedexception e) { the e.printstacktrace (); -                 }Wuyi  the             } -}, "T1"); Wu          -Thread t2 =NewThread (NewRunnable () { About @Override $              Public voidrun () { -                 //synchronized (lock) { -                     if(List2.size ()! = 5){ -                         Try { A                             //System.out.println ("T2 into ..."); +                             //lock.wait (); the countdownlatch.await (); -}Catch(interruptedexception e) { $ e.printstacktrace (); the                         } the                     } theSystem.out.println ("Current thread:" + thread.currentthread (). GetName () + "receive notification thread stop ..."); the                     Throw Newruntimeexception (); -                 //} in             } the}, "T2");  the          About T2.start (); the T1.start (); the          the     } +      -}
View Code

Operation Result:

T2 executes first, obtains the lock lock, and finds the size! = 5 to release the lock lock. The T1 thread starts and wakes another thread t2 when size equals 5, but does not release the lock lock.

If you let T1 execute first, the result will be out of the way. Because T1 got the lock will not be released after the T1 10 cycles before releasing the lock, the size is already 10, T2 execution is late.

But using the wait word has a problem, not real-time, mentioned above, must wait for a thread to execute another line friend receive notification.

It should be replaced with the code Countdownlatch which is not commented out above. An upgraded version that can be understood as notify and wait

Final Run Result:

The architect formed a--5. Communication between threads

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.