"Java Multithreading" mutex

Source: Internet
Author: User

Java multithreaded learning 2--mutex First, preface

In the previous section (http://www.cnblogs.com/lzhen/p/3917966.html), through the implementation of the Runnable interface, you can realize the sharing of resources in multi-threading, solve some basic problems, but in the actual use of the process, Using the methods in section fourth directly produces some unpredictable problems, and now we've made some changes to the code, as follows:

1 classMyThreadImplementsRunnable2 {3  4     Private intTicket = 5;//5 Tickets5  6      Public voidRun ()7     {8          for(inti=0; i<=5; i++) 9         {Ten             if( This. ticket > 0)  One             { ASystem.out.println (Thread.CurrentThread (). GetName () + "Selling tickets" + This. ticket--); -                     Try -                     { theThread.Sleep (500); -                     } -                     Catch(interruptedexception e) -                     { +                         //TODO auto-generated Catch block - e.printstacktrace (); +                     } A  at                 } -             } -         } -      - } -  Public classTestthread { in       -      Public Static voidmain (String [] args) to     { +MyThread my =NewMyThread (); -         NewThread (My, Window No. 1th)). Start (); the         NewThread (My, Window No. 2nd)). Start (); *         NewThread (My, Window No. 3rd)). Start (); $     }Panax Notoginseng}

The result of this code run is:

1 window 1th is selling tickets 5 2 Window 3rd is selling tickets 3 3 window 2nd is selling tickets 4 4 window 2nd is selling tickets 2 5 window 1th is selling tickets 1 6 window 3rd is selling tickets 2

of course, this result is also a great uncertainty, the reason for this problem is that different threads share the same resources when there is a collision, it is possible that thread 1 changed the shared data, before the output, thread 2 has been used, such a problem in practice is not allowed. and mutual exclusion is one of the simplest ways to solve this critical resource problem.

second, synchronized key words

The synchronized keyword is a modifier that can be used to decorate code blocks and methods. Its role is that, for the same object, when different threads call the same method or block of code, they must wait for the previous thread to execute before they can begin executing the method or block of code. , use the Synchronized keyword to modify the above code as follows:

1 Importjava.awt.Desktop.Action;2 3 4 classMyThreadImplementsRunnable5 {6 7     Private intTicket = 5;//5 Tickets8 9 Ten      Public voidRun () One     { A          for(inti = 1; I <= 5; i++) -         { -             synchronized( This) the             { -                 if( This. ticket > 0) -                 { -Action This. Ticket); +                     Try -                     { +Thread.Sleep (500); A                     } at                     Catch(interruptedexception e) -                     { -                         //TODO auto-generated Catch block - e.printstacktrace (); -                     } -                      This. ticket--; in  -                 } to             } +         } -  the     } *  $ Panax Notoginseng      Public synchronized voidActionintticket) -     { theSystem.out.println (Thread.CurrentThread (). GetName () + "Selling tickets" +ticket); +     } A  the } +  -  $  Public classTestthread $ { -  -      Public Static voidMain (string[] args) the     { -MyThread my =NewMyThread ();Wuyi         NewThread (My, Window No. 1th)). Start (); the         NewThread (My, Window No. 2nd)). Start (); -         NewThread (My, Window No. 3rd)). Start (); Wu     } -}

In order to demonstrate the use of synchronized, in the code not only with the synchronized decoration method, but also to decorate the code block, the above code implementation effect is:

Window 1th is selling Ticket number 53rd window is selling ticket 42nd window is selling ticket 33rd window is selling ticket 21st window is selling ticket 1

and the expected effect is consistent.

"Java Multithreading" mutex

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.