Java multi-wire Cheng Gan goods series--------Synchronized__java

Source: Internet
Author: User
Tags finally block modifier mutex object object
Preface

This article focuses on the synchronization in Java multithreading, which is how to write out thread-safe programs in the Java language, and how to troubleshoot issues related to non thread safety in the Java language. Yes, it's using synchronized. Body How to troubleshoot thread safety issues.

So generally speaking, how to solve the problem of thread safety.

Basically all concurrency patterns address thread-safety issues with a "serialized access critical resource" scenario where only one thread accesses a critical resource, also known as synchronous mutex access, at the same time.

Typically, a lock is added to the code that accesses the critical resource, freeing the lock when the critical resource is accessed and allowing other threads to continue accessing it.

In Java, there are two ways to implement synchronous mutex access: synchronized and lock.

This article mainly describes the use of synchronized, the use of lock is described in the next blog post. Synchronized Synchronization Method

Synchronized is a keyword in the Java language that, when used to modify a method or a block of code, ensures that at most one thread at a time executes that segment of code. Before we know how to use the Synchronized keyword, let's look at a concept: a mutex, as the name implies: a lock that reaches a mutually exclusive access purpose.

As a simple example: if you add a mutex to a critical resource, when a thread accesses the critical resource, the other threads can only wait.

In Java, each object has a lock tag (monitor), also known as a monitor, when multithreading accesses an object at the same time, the thread can only access it if it acquires a lock on the object.

In Java, you can use the Synchronized keyword to mark a method or block of code, and when a thread calls the object's synchronized method or accesses the synchronized code block, the thread obtains the lock on the object. Other threads are temporarily unable to access this method, and the thread will not release the lock of the object until the method is finished or the code block executes, and other threads can execute the method or block of code. the use of synchronized

Synchronized code block, the modified code to become a synchronized statement block, the scope of the function is to call the code block object, we use the Synchronized keyword, we can narrow the scope of the Code section as far as possible, can be added to the Code section on the synchronization will not be added to the whole method of synchronization. This is called reducing the size of the lock to make the code more concurrent.

Synchronized method, the modified method becomes the synchronization method, whose scope is the whole method, and the object is the object that calls the method.

Synchronized a static method that modifies a static method that is scoped to the entire static method, and the object is all objects of the class.

The synchronized class, which is scoped to the part of the synchronized followed by parentheses synchronized (Classname.class), is the object of all objects of this class.

Synchronized (), () is a locked object, synchronized (this) locks only the object itself, the Synchronized method invoked by the different objects of the same class is not locked, and synchronized ( Classname.class) implements the global lock function, all this class object calls this method to be affected by the lock, moreover () also may add a concrete object, realizes to the concrete object lock.

Synchronized (object) {
//operation of objects in a synchronized code block
}
synchronized matters needing attention

When two concurrent threads access a synchronized code block in the same object, only one thread can be executed at the same time and another thread is blocked, and the code block must wait until the current thread has finished executing the code block. Two threads are mutually exclusive, because the current object is locked when the synchronized code block is executed, and the next thread can execute and lock the object only if the block of code is executed to release the object lock.

When a thread accesses a synchronized (this) synchronization code block of object, another thread can still access a non-synchronized (this) synchronized code block in that object. (Two threads use the same object) when a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized blocks in object is blocked (Ibid., Two threads are using the same object.

The following code is used to implement:

1 when two concurrent threads access the synchronized (this) synchronized code block in the same object, only one thread can be executed at a time. Another thread must wait until the current thread finishes executing the code block before executing the code block.

package ths;

public class Thread1 implements Runnable {public  
     void run () {  
          synchronized (.) {for  
               (int i = 0; i < 5; i++) {  
                    System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i);  
               }  
          }  
     public static void Main (string[] args) {  
          Thread1 t1 = new Thread1 ();  
          Thread ta = new Thread (T1, "A");  
          Thread TB = new Thread (T1, "B");  
          Ta.start ();  
          Tb.start ();  
     } 

Output results:

A synchronized loop 0  
a synchronized Loop 1  
a synchronized loop 2  
A synchronized loop 3  
A synchronized Loo P 4  
B synchronized loop 0  
b synchronized loop 1  
B synchronized loop 2  
b synchronized loop 3  
b Synchron Ized Loop 4

2 However, when a thread accesses a synchronized (this) synchronization code block of object, another thread can still access a non-synchronized (this) synchronized code block in that object.

package ths;  
               public class Thread2 {public void m4t1 () {synchronized () {int i = 5;  
                    while (i--> 0) {System.out.println (Thread.CurrentThread (). GetName () + ":" + i);  
                    try {thread.sleep (500); catch (Interruptedexception IE) {}}} public void M  
          4t2 () {int i = 5;  
               while (i--> 0) {System.out.println (Thread.CurrentThread (). GetName () + ":" + i);  
               try {thread.sleep (500); ' catch (Interruptedexception IE) {}} ' public static void main (string[] args  
          ) {final Thread2 myt2 = new Thread2 ();  thread T1 = new Thread (new Runnable () {public void run () {myt2.m4t1 ());  
          }, "T1"); Thread t2 = New Thread (New Runnable () {public void run () {myt2.m4t2 ();  
          }, "T2");  
          T1.start ();  
     T2.start (); } 
}

Output results:

T1:4  
t2:4  
t1:3  
t2:3  
t1:2  
t2:2  
t1:1 t2:1 t1:0 t2:0

3 in particular, when a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized code blocks in object is blocked by other threads.

Modify the Thread2.m4t2 () method: public  
     void M4t2 () {  
          synchronized (this) {  
               int i = 5;  
               while (i--> 0) {  
                    System.out.println (Thread.CurrentThread (). GetName () + ":" + i);  
                    try {  
                         thread.sleep;  
                    } catch (Interruptedexception IE) {  
                    }

     }}

Output results:

T1:4  
t1:3  
t1:2  
t1:1  
t1:0  
t2:4  
t2:3 t2:2 t2:1 t2:0

4 The third example also applies to other synchronized code blocks. That is, when a thread accesses a synchronized (this) synchronization code block of object, it obtains the object lock of the objects. As a result, access to all of the synchronization code portions of the object object by other threads is temporarily blocked.

Modify the Thread2.m4t2 () method as follows: public

     synchronized void M4t2 () {  
          int i = 5;  
          while (i--> 0) {  
               System.out.println (Thread.CurrentThread (). GetName () + ":" + i);  
               try {  
                    thread.sleep;  
               } catch (Interruptedexception IE) {  
               }  
     }}

Output results:

T1:4  
t1:3  
t1:2  
t1:1  
t1:0  
t2:4  
t2:3 t2:2 t2:1 t2:0

5) Each class also has a lock that can be used to control concurrent access to static data members.
and if one thread executes an object's synchronized method, and another thread needs to execute the static synchronized method of the class to which the object belongs, there is no mutex at this point because the access static The synchronized method occupies a class lock, while access to the non-static synchronized method occupies an object lock, so there is no mutex. The
code is as follows:

public class Test {public static void main (string[] args) {final InsertData insertdata = new InsertData ();
            New Thread () {@Override public void run () {Insertdata.insert (); 
        }}.start ();
            New Thread () {@Override public void run () {insertdata.insert1 ();
    }}.start ();
        } class InsertData {public synchronized void Insert () {System.out.println ("execute Insert");
        try {thread.sleep (5000);
        catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("Execute insert Complete");
        Public synchronized static void Insert1 () {System.out.println ("execute Insert1");
    System.out.println ("Execution Insert1 completed"); }
}

Output results:

Execute insert
execution Insert1
execute insert1 finish
insert complete

The Insert method is executed inside the first thread and does not cause the second thread to perform a blocking behavior on the Insert1 method. Face Test

When a thread enters the synchronized method A of an object, whether other threads can enter synchronized method B of this object.
Answer: No. Other threads can access only the asynchronous method of the object, and the synchronization method cannot enter. Because the synchronized modifier on a non-static method requires that the object's lock be obtained when the method is executed, the thread attempting to enter the B method can only wait for the object's lock in the lock pool (note that it is not the waiting pool) if the object lock has been taken away.

The use of synchronized keywords.
A: The Synchronized keyword can mark objects or methods as synchronized to achieve mutually exclusive access to objects and methods, and you can use synchronized (object) {...} Defines a synchronized code block, or synchronized as a method modifier when declaring a method.

The similarities and differences of synchronized and Java.util.concurrent.locks.Lock are briefly described.
A: Lock is the new API introduced after Java 5, which is the main same point compared to the keyword synchronized: lock completes all the functions that synchronized implements Main differences: Lock has more precise line Cheng and better performance than synchronized, and it's not mandatory to get lock. Synchronized will automatically release the lock, and lock must require the programmer to manually release it, and it is best to release it in the Finally block (this is the best place to release external resources)

The above is the concept of synchronized and basic usage, the next blog will introduce lock, hope to help you.

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.