Basic usage of synchronized keywords in Java multithreaded programming _java

Source: Internet
Author: User
Tags thread class

Multithreaded programming, the most critical and most concerned about the problem should be synchronization, which is a difficult and core.
from JDK's earliest versions of synchronized, volatile, to JDK 1.5 in the Java.util.concurrent.locks package in the lock interface (Implementation has readlock,writelock,reentrantlock), multi-threaded implementation is also a step-by-step towards maturity.
 
Synchronization, what mechanism does it control? The first reaction is the lock, which should have been contacted when learning the operating system and database. In Java multithreaded programs, when multiple programs compete for the same resource, the first resource-access thread is assigned an object lock to prevent the corruption of the resource, and the latter needs to wait for the lock to be released.
 
Yes, the synchronization of Java threads is most concerned with the use of shared resources.
&NBSP
First to understand some of the threads of shared resources,
from the JVM to know what threads are sharing data that needs to be coordinated:
1, the instance variable saved in the heap, 2, the class variable saved in the method area.
&NBSP
While the Java Virtual machine loads a class, each object or class is associated with a monitor that protects an object's instance variables or class variables; Of course, if the object has no instance variables, or if the class has no variables, the monitor is not monitoring anything.
&NBSP
The virtual machine associates a lock (also known as a stealth lock) for each object or class, in order to achieve the mutex of the monitor described above, which illustrates that class locks are also implemented through object locks, because when a class is loaded, The JVM creates an instance of Java.lang.Class for each class, so when the lock is on the object, the class object of the class is locked.
 
In addition, a thread can lock a single object multiple times, and it is a lock calculator that is provided through the JVM for each object, and the last lock is added 1, minus 1, and released when the calculator's value is 0 o'clock. This object lock is used by the monitor inside the JVM and is automatically generated by the JVM, and all programs will not have to be added by themselves.
&NBSP
After introducing the principle of Java synchronization, let's go to the point where we'll talk about the use of synchronized, and the other synchronizations will be covered in later chapters.
 
To run an example first try.

Package thread_test; 
 
/** 
 * Test Extended thread class implementation of multithreaded 
 * * * 
/public class Testthread extends thread{  
  private int threadnum; 
 
  Public testthread (int threadnum) {  
    this.threadnum = threadnum;  
  } 
   
  @Override public 
  synchronized void Run () {for  
    (int i = 0;i<1000;i++) {  
          System.out.println ("NO." + Threadnum + ":" + i); 
    }  
   
    public static void Main (string[] args) throws Exception {for  
      (int i=0; i<10; i++) { 
          new Testthread (i). Start () ; 
          Thread.Sleep (1); 
      }}}  
 


Run Result:

no.0:887 
no.0:888 
no.0:889 
no.0:890 
no.0:891 
no.0:892 no.0:893 no.0:894 
no.7:122 
no.7:123 
no.7:124 

The above is just a fragment that illustrates a problem.
Careful child shoes will find that the no.0:894 behind is no.7:122, that is, not in accordance with starting from 0 to 999. The
says that synchronized can implement synchronization methods or sync blocks, so why not here?
 
First, from the mechanism of synchronization to analyze the synchronization is implemented by the lock, then in the example above, what object is locked, or what class is locked? There are two variables, one is I, one is Threadnum;i is the method internal, Threadnum is private.
to learn more about synchronized's operating mechanism:
      in Java programs, when using synchronized blocks or synchronized methods, Flag this area for monitoring, and the JVM automatically locks the object or class when the program is in the monitoring area when it processes the program.
 
So in the above example, what is locked after the synchronized keyword is used?
when the synchronized method is locked, the instance object that calls the method is itself an object lock. In this case, all 10 threads have their own Testthread class objects created, so the object lock they get is also their own object lock, which has nothing to do with other threads.
&NBSP
To implement a method lock, the shared object must be locked.
&NBSP
To modify the example above, and then look at the following:

Package thread_test; 
 
/** 
 * Test Extended thread class implementation of multithreaded 
 * * * 
/public class Testthread extends thread{  
  private int threadnum; 
  Private String flag;  Tag public 
   
  testthread (int threadnum,string flag) {  
       this.threadnum = threadnum;  
        This.flag = Flag; 
    } 
   
  @Override public 
    Void Run () {  
    synchronized (flag) {for 
      (int i = 0;i<1000;i++)  
              { System.out.println ("NO." + Threadnum + ":" + i);  
 
    }}} public static void Main (string[] args) throws Exception {  
      string flag = new String ("flag"); 
      for (int i=0; i<10; i++) { 
          new Testthread (I,flag). Start (); 
          Thread.Sleep (1); 
      }}}  
 


Also adds a share of the logo flag. The flag flag is then synchronized through the synchronized block, which satisfies the criteria for locking the shared object.
Yes, the results of the operation have come in order.

The

uses the synchronized block to specify that the object lock is acquired to achieve synchronization purposes. Is there any other way that can be achieved by synchronized method?
&NBSP
is based on the principle of synchronization: If you can get a shared object lock or class lock, and you can implement synchronization. So is it possible to share a class lock?
 
Yes, we can use a static synchronization method that, depending on the nature of the static method, only allows the class object itself to be invoked and cannot be invoked by instantiating a class object. So if the lock of this static method is obtained, that is to obtain the class lock, which is the Testthread class lock and achieves the purpose of acquiring the shared class lock. The
 
Implementation code is as follows:

Package thread_test; 
 
/** 
 * Test Extended thread class implementation of multithreaded * * 
 @author ciding 
 * @createTime Dec 7, 9:37:25 AM 
 * * 
* public class Testthread extends thread{  
  private int threadnum; 
   
  Public testthread (int threadnum) {  
    this.threadnum = threadnum;  
  } 
   
  public static synchronized void statictest (int threadnum) {for  
    (int i = 0;i<1000;i++) {  
      System.out.println ( "NO." + Threadnum + ":" + i); 
    }  
 
  public static void Main (string[] args) throws Exception {for  
    (int i=0; i<10; i++) { 
      new Testthread (i). Start () ; 
      Thread.Sleep (1); 
    } 
  }  
   
  @Override public 
  Void Run () { 
    statictest (threadnum); 
  } 
} 

The results of the operation are slightly the same as in the second example.


The above content is mainly explained two questions: synchronized block and synchronization method.
1, sync block: Gets the object lock is the flag object lock in synchronized (flag).
2, synchronization method: Gets the class object that the method belongs to, and the class object lock.
Static synchronization methods, which are shared by multiple threads, must be synchronized.
Instead of a static synchronization method, it is synchronized only in single case mode.

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.