Java multithreading (6) Explanation of synchronized keywords and synchronized keywords

Source: Internet
Author: User

Java multithreading (6) Explanation of synchronized keywords and synchronized keywords
Java multithreading (6) Explanation of synchronized keywords

The multi-thread synchronization mechanism locks resources so that only one thread can operate at the same time. synchronization is used to solve problems that may occur when multiple threads access the resources simultaneously.

Synchronization mechanism can be usedSynchronized keyword.

  When the synchronized keyword modifies a method, this method is called a synchronous method.

When the synchronized method is executed 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 example programs with the synchronized keyword 1

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 <10; ++ I)
{
Try
{
Thread. sleep (500 );
}
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.exe cute ();
}

}

 

Is it added before the execute () method?SynchronizedKeyword. The execution results of the program in this example are very different.

  If the synchronized keyword is not added, The two threads execute the execute () method at the same time, and the output is two sets of concurrency.

  If the synchronized keyword is addedFirst, a group of 0 to 9 is output, and then the next group is output, indicating that the two threads are executed sequentially.

 

2. multithreading of multiple methods

Change the program and add the execute2 () method to the Example class ().

Then write a Thread class Thread2. The run () method in Thread2 executes execute2 (). Both methods in the Example class are modified by the synchronized keyword.

Example 2
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 < 20; ++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 < 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();    }}

If the synchronized keyword is removed, the two methods are executed concurrently without affecting each other.

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

  The execution result is always the output of one thread and then the output of another thread.  

Note:

  If an object has multiple synchronized methods, a thread enters a synchronized method at a certain time point, before the method is executed, other threads cannot access any synchronized Method of this object.

  Conclusion:

When the synchronized keyword modifies a method, this method is called a synchronous method.

Every object in Java has a lock or monitor. When a thread accesses the synchronized Method of an object,Lock this object, No other thread can access the object's synchronized Method again (this refers to all the synchronization methods, not just the same method ), the lock of the object is released only after the previous thread executes the method (or throws an exception). Other threads can access the synchronized Method of the object.

Note thatLock objectsFor different objects, there is no restriction between objects.

When you try to construct a second thread object in the Code and input a new Example object, there is no restriction between the two threads.

3. Static Synchronization Methods

When a synchronized keyword modifier method is modified at the same time by static, as mentioned earlier, non-static Synchronization Methods lock objects, but static methods do not belong to objects, but belong to Classes.Set the CLassObject lock.

  A Class corresponds to the same Class Object no matter how many objects are generated.

Example 3
Public class ThreadTest {public static void main (String [] args) {Example example = new Example (); Thread t1 = new Thread1 (example ); // even if different objects are passed in, static method synchronization still does not allow multiple threads to execute 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) {try {Thread. sleep (long) Math. random () * 1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("Hello:" + I) ;}} public synchronized static void execute2 () {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.exe cute () ;}} class Thread2 extends Thread {private Example example Example; public Thread2 (example) {this. example = example ;}@ Override public void run () {Example.exe cute2 ();}}

 

Therefore, in the case of static methods (execute () and execute2 () both add the static keyword), even if different Example objects are introduced to two threads, the two threads are still mutually restricted, you must finish executing one before executing the next one.

 

  Conclusion:

If a synchronized method is static, when a thread accesses this method, it does not lock the object of the synchronized method, but the Class object corresponding to the Class of the synchronized method. In Java, no matter how many objects a Class has, these objects correspond to a unique Class Object. Therefore, when the thread accesses the two static and synchronized methods of the two objects of the same Class respectively, their execution order is also sequential, that is, one thread first executes the method, and the other thread starts after the execution is complete.

 

4. synchronized Block

Synchronized block Syntax:

Synchronized (object)

{

}

Indicates that the thread locks the object during execution. (Note that this object can be an object of any class or use the this keyword ).

In this way, you can define the Lock Object on your own.

 

Example 4
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 < 20; ++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();    }}

The same effect achieved by example program 4 and example Program 2 is that the execution sequence of the two threads is performed, rather than concurrently. When a thread is executed, the object is locked, another thread cannot execute the corresponding block.

The synchronized method is equivalent to using a synchronized block to wrap all the statements in the method, and then passing the this keyword in the brackets of the synchronized block. Of course, if it is a static method, the class object needs to be locked.

  

Only a few lines of code in a method may involve thread synchronization. Therefore, synchronized blocks control the access of multiple threads in a more fine-grained manner than the synchronized method, only the content in the synchronized block cannot be accessed by multiple threads at the same time. Other statements in the method can still be accessed by multiple threads at the same time (including those before and after the synchronized block ).

Note: The data protected by synchronized should bePrivate.

  Conclusion:

  Synchronized MethodIs a coarse-grained concurrency control. at a specific time, only one thread can execute the synchronized method;

  Synchronized BlockIt is a fine-grained concurrency control that only synchronizes the code in the block. Other code located in the method and outside the synchronized block can be accessed by multiple threads at the same time.

Release and release of JDK 5.0

Using the synchronized keyword to solve the thread synchronization problem may cause some execution efficiency problems.

JDK1.4 and previously cannot avoid these problems.

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 solve this problem.

This article will not be introduced here.

References

Shengsiyuan Zhang Long's Java SE series video tutorial.

 

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

 

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.