Multi-threaded synchronization

Source: Internet
Author: User
Tags ticket

Problem Introduction: Thread Security issues

The following procedure finds that there are No. 0 or even minus votes, because of the thread safety problem caused by the multi-threaded operation sharing resource saletask.

1 classExample12 {3      Public Static voidMain (string[] args)4     {5Saletask Saletask =NewSaletask ();//Create a Saletask object6         //create four threads and start7         NewThread (saletask, "window One"). Start ();8         NewThread (saletask, "window two"). Start ();9         NewThread (saletask, "window three"). Start ();Ten         NewThread (Saletask, "window four"). Start (); One          A     } - } -  the //defining the Salethread class to implement the Runnable interface - classSaletaskImplementsRunnable - { -     Private intTickets = 10; +      Public voidRun () -     { +          while(tickets>0){ A             Try{ atThread.Sleep (10);//the second transfer thread sleeps 10 milliseconds, simulating a ticket delay.  -}Catch(interruptedexception e) { - e.printstacktrace (); -             } -System.out.println (Thread.CurrentThread (). GetName () + "... sales ..." +tickets--); -          } in     } -}

Problem solving: Synchronizing code blocks or synchronizing methods

Thread-safety issues are actually caused by multiple threads processing shared resources at the same time. To solve this problem, you must ensure that the code used to process the shared resource can only have one thread access at any point in time.

To implement this limitation, the synchronization mechanism is provided in Java. When multiple threads use the same shared resource, the code that handles the shared resource can be placed in a block of code, decorated with the synchronized keyword, called a synchronous code block, with the following syntax:

synchronized (lock) {   manipulate code blocks for shared resources}

In the above code, lock is a lock object, which is the key to synchronizing code blocks. When a thread executes a synchronized code block, the lock object's flag bit is first checked, the flag bit is 1 by default, and the thread executes the synchronized code block while the lock object's flag position is 0. When a new thread executes into this block of synchronization code, because the lock object's flag bit is 0, the new thread blocks, waits for the current thread to finish executing the synchronization code block, the lock object's flag bit is set to 1, and the new thread can enter the code in which the synchronization code block executes. Until the shared resource is processed. This process is like a public phone box, only the front of a person after the call came out, the back of the people can go in to call.

The following is a procedure for improving the program with synchronous code blocks:

1 classExample22 {3      Public Static voidMain (string[] args)4     {5Ticket1 ticket =NewTicket1 ();6         NewThread (Ticket, "window one"). Start ();7         NewThread (Ticket, "window two"). Start ();8         NewThread (Ticket, "window three"). Start ();9         NewThread (Ticket, "window four"). Start ();Ten          One     } A } -  -  the classTicket1ImplementsRunnable - { -     Private intTickets = 10; -Object lock =NewObject ();//define any object, as a lock of the synchronization code block, must be placed outside the Run Method!  +      Public voidRun () -     { +          while(true){ A             synchronized(lock) {//defining a synchronization code block at              Try{ -Thread.Sleep (10); -}Catch(interruptedexception e) { - e.printstacktrace (); -                   } -               if(tickets>0){ inSystem.out.println (Thread.CurrentThread (). GetName () + "... sales ..." +tickets--); -}Else{ to                        Break; +                } -          } the       } *    } $}

Note: the lock object in a synchronization code block can be any type of object, but the lock objects shared by multiple threads must be unique.

Synchronization method

You can also use the Synchronized keyword to decorate the method before, and the modified method is the synchronous method, which can implement the same function as synchronizing the code block.

A method that is modified by synchronized only allows one thread to access at a time, and other threads that access the method are blocked until the current thread has finished accessing it, and other threads have the opportunity to execute the method.

Use the following:

1 classExample32 {3      Public Static voidMain (string[] args)4     {5Ticket1 ticket =NewTicket1 ();6         NewThread (Ticket, "window one"). Start ();7         NewThread (Ticket, "window two"). Start ();8         NewThread (Ticket, "window three"). Start ();9         NewThread (Ticket, "window four"). Start ();Ten          One     } A } -  -  the classTicket1ImplementsRunnable - { -     Private intTickets = 10; -      Public voidRun () +     { -          while(true){ +Saleticket ();//Call ticket Method A             if(tickets<=0){ at                   Break; -               } -          } -      } -  -     //define a synchronization method Saleticket () in     Private synchronized voidSaleticket () -     { to         if(tickets>0) +         { -              Try{ theThread.Sleep (10); *}Catch(interruptedexception e) { $ e.printstacktrace ();Panax Notoginseng                   } -System.out.println (Thread.CurrentThread (). GetName () + "... sales ..." +tickets--); the         } +      A     } the }              +                  

The lock of the synchronous method is the object that is currently calling the method, which is the object that this is pointing to. The advantage of this is that the synchronization method is shared by all threads, and the method's object is unique to all threads, guaranteeing the uniqueness of the lock. When a thread executes the method, other threads cannot enter the method until the thread has finished executing the method, thus achieving the effect of thread synchronization.

Static synchronization functions in memory when the object does not exist, but there is a class of its own bytecode file object, is a class type of object, so the static synchronization function of the lock is the class of its own bytecode file object, the object can be directly used "class name." Way to get.

Summarize:

Synchronization solves a thread-safety problem when multiple threads concurrently access shared data, and only one thread can execute at the same time, as long as the same lock is added. However, the thread will judge the state of the lock every time it executes the synchronization code, which is very resource-intensive and less efficient.

Multi-threaded synchronization

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.