Java Concurrency Programming-synchronized

Source: Internet
Author: User
Tags object object thread class

Multi-threaded synchronization mechanism to lock the resources, so that at the same time, only one thread can operate, synchronous to solve the problem that can occur when multiple threads concurrently access.
The synchronization mechanism can be implemented using the SYNCHRONIZED keyword.
When the Synchronized keyword modifies a method, the method is called a synchronous method.
When the Synchronized method finishes executing or an exception occurs, the lock is automatically released.
Synchronized can be used to modify common methods (equivalent to synchronized (this)), static methods (equivalent to synchronized (aa.class)), and synchronization blocks ( Synchronized (object)).
The following example is used to parse the usage of the Synchronized keyword.
1. Whether to use different synchronized keywords

[Java]public class threadtest{    public static void Main (string[] args)     {         Example Example = new Example ();        Thread T1 = new Thread1 (example);        Thread t2 = new Thread1 (example);         T1.start ();        T2.start ();    }}class example{    public synchronized Void execute ()     {         for (int i = 0; i < ++i)         {  & nbsp;         try             {                Thread.Sleep (+);           }            catch (interruptedexception e)              {                 e.printstacktrace ();           }             System.out.println ("Hello:" + i);        }   }}class Thread1 extends thread{    private Example example;    Public Thread1 (example example)     {         this.example = example;   }    @Override     public void Run ()     {        example.execute ();   }}[/java]

If the

is preceded by the Execute () method with the Synchronized keyword, the execution result of this example program will vary greatly.
If you do not add the Synchronized keyword, two threads execute the Execute () method at the same time, and the output is two sets of concurrency.
If you add the Synchronized keyword, you will first output a set of 0 to 9 and then output the next set, which means that two threads are executed sequentially.
2. Multi-threaded case of multiple methods
Change the program, and then add a method Execute2 () to the example class.
then write a thread class The run () method in Thread2,thread2 executes Execute2 (). The two methods in the example class are decorated with the synchronized keyword.

[Java]public class threadtest{    public static void Main (string[] args)     {         Example Example = new Example ();        Thread T1 = new Thread1 (example);        Thread t2 = new Thread2 (example);         T1.start ();        T2.start ();    }}class example{    public synchronized Void execute ()     {         for (int i = 0; i < ++i)         {  & nbsp;         try             {                Thread.Sleep ((Long) math.random () * +);           &nbsp }            catch (interruptedexception e)              {                 e.printstacktrace ();            }            System.out.println ("Hello:" + i);        }   }    public synchronized void Execute2 ()     {        for (int i = 0; i < ++i)          {            try             {                 Thread.Sleep ((Long) math.random () * +);            }             catch (interruptedexception e)             {                 e.printstacktrace ();            }             System.out.println ("World:" + i);       }    }}class Thread1 extends thread{    private Example example;    public Thread1 (Example Example)     {        this.example = example;   }     @Override     public void Run ()     {         Example.execute ();   }}class Thread2 extends thread{    pRivate Example example;    public Thread2 (Example Example)     {         this.example = example;   }    @Override     public void Run ()     {        example.execute2 ();    }}[/java]

If you remove the Synchronized keyword, the two methods execute concurrently and do not affect each other.
However, as is written in the example program, even two methods:
The result of execution is always executing the output of one thread before executing another thread.
Description:
If an object has multiple synchronized methods, and a thread has entered a synchronized method at some point, the other thread is unable to access any of the synchronized methods of the object until the method has finished executing.
Conclusion:
When the Synchronized keyword modifies a method, the method is called a synchronous method.
Each object in Java has a lock, or monitor, that locks the object when a thread accesses the synchronized method of an object. No other thread can access the object's Synchronized method (this refers to all synchronous methods, not just the same method) until the previous thread executes the method (or throws an exception) before releasing the object's lock. Other threads will be able to access the object's synchronized method again.
Note that this is a lock on the object, and if it is a different object, there is no restriction between the objects.
when attempting to construct a second thread object in code, a new example object is passed in, and there is no restriction between the execution of the two threads.
3. Consider a static synchronization method
When a synchronized keyword-modified method is also modified by static, it is said that a non-static synchronization method locks the object, but the static method does not belong to the object, but belongs to the class. It locks the class object of the classes in which the method resides.
A class, regardless of how many objects are generated, corresponds to the same class object.

[Java]public class threadtest{    public static void Main (string[] args)     {         Example Example = new Example ();        Thread T1 = new Thread1 (example);       //Here static method synchronization does not allow multiple threads to execute simultaneously even if different objects are passed in          example = new Example ();        Thread t2 = New Thread2 (example);        T1.start ();         T2.start ();   }}class example{    public synchronized static void execute ()     {        for (int i = 0; I <20; ++i)     & nbsp;   {            try             {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;        Thread.Sleep (Long) math.random () * +);            }            catch (interruptedexception e)             {                 e.printstacktrace ();            }             System.out.println ("Hello:" + i);       }   }     public synchronized static void Execute2 ()     {         for (int i = 0; I <20; ++i)         {     & nbsp;      try             {                Thread.sleep (Long) Math.random () *;           }             catch (interruptedexception e)              {                 e.printstacktrace ();           }             System.out.println ("World:" + i);        }   }}class Thread1 extends thread{    private Example example;    Public Thread1 (example example)     {         This.example = example;   }    @Override     public voidRun ()     {        example.execute ();   }}class Thread2 extends thread{    private Example example;    public Thread2 (Example Example) & nbsp;   {        this.example = example;   }     @Override     public void Run ()     {         Example.execute2 ();   }}[/java]

So if it is a static method (execute () and Execute2 () plus the static keyword), even if you pass in a different example object to two threads, the two threads are still constrained by each other, and you must execute one before executing the next.
Conclusion:
If a synchronized method is static, then when the thread accesses the method, it locks not the object that the Synchronized method resides in, but the class object that corresponds to the synchronized method. In Java, no matter how many objects a class has, these objects correspond to a unique class object, so when a thread accesses two static,synchronized methods of two objects of the same class individually, their order of execution is also sequential, that is, a thread first executes the method, Another thread does not start until after execution is complete.
4. Synchronized block
Synchronized block notation:

[Java]synchronized (object) {}[/java]

Indicates that the thread will lock object object when executing. (Note that this object can be an object of any class, or you can use the This keyword).
This allows you to set your own lock object.

[Java]public class threadtest{    public static void Main (string[] args)     {         Example Example = new Example ();        Thread T1 = new Thread1 (example);        Thread t2 = new Thread2 (example);         T1.start ();        T2.start ();    }}class example{    Private Object object = new Object ();    public void Execu Te ()     {        synchronized (object)          {            for (int i = 0; i < ++i) & nbsp;           {                 TRY&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;         {                     Thread.Sleep ((Long) math.random () * +);                }                 catch (interruptedexception e)                 {                     e.printstacktrace ();                }                 System.out.println ("Hello:" + i);            }       }    }    public void Execute2 ()     {        synchronized (object)         {             for (int i = 0; i < ++i)             { & nbsp;              try                 {                     Thread.Sleep ((Long) math.random () * 1000) ;               }                 catch (interruptedexception e)                  {                    E.printstacktrace ();                }                System.out.println ( "World:" + i);           }        }   }}class Thread1 extends thread{    private Example example;     public Thread1 (Example Example)     {        This.example = example;   }    @Override     public void run ()      {        example.execute ();   }}class Thread2 Extends thread{    private Example example;    public Thread2 (Example Example)      {        this.example = example;   }    @Override     public void Run ()     {        Example.execute2 ();   }}[/java]

Example program 4 achieves the same effect as the example program 2, is to make the execution order of two threads, not concurrency, when one thread executes, the object is locked, the other thread cannot execute the corresponding block.
The Synchronized method is actually equivalent to wrapping all the statements in the method with a synchronized block, and then passing in the This keyword in parentheses in the synchronized block. Of course, if it is a static method, it is a class object that needs to be locked.
Perhaps only a few lines of code in a method will involve thread synchronization problems, so the synchronized block is more granular than the Synchronized method to control access to multiple threads, and only the contents of the synchronized block cannot be accessed by multiple threads at the same time. The other statements in the method can still be accessed by multiple threads at the same time (both before and after the synchronized block).
Note: Data that is protected by synchronized should be private.
Conclusion:
The synchronized method is a coarse-grained concurrency control where only one thread can execute the synchronized method at a time;
The synchronized block is a fine-grained concurrency control that synchronizes code in the block only, and other code that is inside the method and outside the synchronized block can be accessed concurrently by multiple threads.
Concurrent packages for JDK 5.0
Resolving thread synchronization problems with the Synchronized keyword can lead to some execution efficiency problems.
These problems cannot be avoided by JDK1.4 and before.
JDK 5.0 introduces such a package: Java.util.concurrent:
Http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-frame.html
Specifically address this issue.

Java Concurrency Programming-synchronized

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.