Java Synchronised keywords

Source: Internet
Author: User
Tags object object thread class java se

Transferred from: http://www.cnblogs.com/mengdd/archive/2013/02/16/2913806.html

Java Multithreading (vi) synchronized keyword details java multithreading (vi) SYNCHRONIZED keyword

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 or an exception occurs, the lock is automatically released.

The following example is used to parse the usage of the Synchronized keyword.

1. Whether to use different synchronized keywords
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)        {            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 ();    }}

If you add the synchronized keyword before the Execute () method, the execution result of this example program will be very different.

  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. Multithreading scenarios for multiple methods

To change the program, add a Method Execute2 () to the example class.

Then write a thread class thread2,thread2 the Run () method executes the Execute2 (). The two methods in the example class are decorated with the synchronized keyword.

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) {try            {Thread.Sleep (long) math.random () * 1000);            } 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 () * 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 (); }}

If you remove the Synchronized keyword, the two methods are executed concurrently and do not affect each other.

However, even two methods are written in the example program:

  The execution result is always executing the output of one thread and then 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 trying to construct a second thread object in code, passing in a new example object, 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, the non-static synchronization method locks the object, but the static method does not belong to the object, but belongs to the class, which will place the Class of the class where the method resides. The object is locked .

  A class, regardless of how many objects are generated, corresponds to the same class object.

Example Program 3

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:

Synchronized (object)

{

}

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.

 

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 execute () {synchronized (object) {for (int i = 0; i <; ++i) {                try {thread.sleep (long) math.random () * 1000);                } catch (Interruptedexception e) {e.printstacktrace ();            } System.out.println ("Hello:" + i);  }}} public void Execute2 () {synchronized (object) {for (int i = 0; i < 20;                ++i) {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 (); }}

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.

Confined to space, no longer described here.

Resources

Santhiya Garden Zhang Long teacher Java SE Series video tutorial.

(GO) Java synchronised keyword

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.