The usage of synchronized in Java (four uses) _java

Source: Internet
Author: User
Tags int size

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 the same time executes that segment of code.

1. When using the method declaration, after the range operator (public, and so on) is returned, before the type declaration (void, and so on) is received. At this point, the thread obtains the member lock, that is, only one thread can enter the method at a time, and other threads can only wait in line to call the method at this time It is the thread within the Synchronized method that finishes the method before another thread can enter.

For example:

   Public synchronized void Synmethod () {
    //method body
   }

2. Used for a block of code, synchronized followed by parentheses, and a variable in parentheses, so that only one thread at a time enters the code block. At this point, the thread gets a member lock. For example:

   public int Synmethod (int a1) {
    synchronized (A1) {
     //Only one thread can enter} at a time
    }
   

3.synchronized the back bracket is an object, at which point the thread obtains an object lock. For example:

 public class Mythread implements Runnable {public
  static void Main (String args[]) {
  mythread mt = new Mythread ();
  thread T1 = new Thread (MT, "T1");
  Thread t2 = new Thread (MT, "T2");
  thread t3 = new Thread (MT, "T3");
  thread T4 = new Thread (MT, "T4");
  Thread T5 = new Thread (MT, "T5");
  Thread T6 = new Thread (MT, "T6");
  T1.start ();
  T2.start ();
  T3.start ();
  T4.start ();
  T5.start ();
  T6.start ();
 }
 public void Run () {
  synchronized (this) {
   System.out.println (Thread.CurrentThread (). GetName ());
  }
 

For 3, if the thread enters, the current object lock is obtained, and no action of any other thread on all of the objects in the class is possible. Using locks at the object level is usually a rough method. Why should the entire object be locked instead of allowing other threads to temporarily use other synchronization methods in the object to access the shared resource? If an object has more than one resource, it does not need to lock all threads out just to allow one thread to use one of the resources. Because each object has a lock, you can use the virtual object to lock as follows:

Class Finegrainlock {
  mymemberclass x, y;
  Object Xlock = new Object (), Ylock = new Object ();
  public void Foo () {
   synchronized (xlock) {
     //access x to
   }
   //do something here-but don ' t use shared res Ources
   synchronized (ylock) {
     //access y
   }
  } public
  void Bar () {
   synchronized (this) {
     //access both X and y here
   }
   Do something here-but don ' t with shared resources
  }
 

4.synchronized followed by a class in parentheses, at which point the thread obtains an object lock. For example:

Class arraywithlockorder{private static Long num_locks = 0;
 Private long Lock_order;
 Private int[] arr;
  Public Arraywithlockorder (int[] a) {arr = A;       Synchronized (Arraywithlockorder.class) {//-----here num_locks++;
   Lock number plus 1. Lock_order = Num_locks;
  Sets the unique lock_order for this object instance.
 } public Long Lockorder () {return lock_order;
 Public int[] Array () {return arr; } class SomeClass implements Runnable {public int sumarrays (Arraywithlockorder A1, Arraywithlockorder a
  2) {int value = 0;    Arraywithlockorder-A1;    Preserves an array reference to a arraywithlockorder last = A2;
  Local copy.
  int size = A1.array (). length; 
    if (size = = A2.array (). Length) {if (A1.lockorder () > A2.lockorder ())//Determine and set the lock {//order of the object.
    i = A2;
   last = A1;
    Synchronized (i) {//Lock objects in the correct order.
     Synchronized (last) {int[] arr1 = A1.array ();
     int[] arr2 = A2.array (); for (int i=0; i<size; i++) vaLue + = Arr1[i] + arr2[i];
 }} return value; public void Run () {//}}

For 4, if a thread enters, the thread cannot do all the operations in the class, including static variables and static methods, and in fact, we usually use 4来 for synchronization of code blocks that contain static methods and static variables.

Summary of ps:synchronized Usage

Synchronized the impact of the use of different places on the code:

1. Synchronized keyword Modification method

Assuming that P1, P2 are different objects of the same class, this class defines synchronization blocks or synchronization methods for the following situations, and P1 and P2 can call them.

Public synchronized void Method () {
  // 
}

This is the synchronous method, when the synchronized lock is called to the synchronization method object. That is, when an object P1 the synchronization method in a different thread, they form a mutex that achieves the effect of synchronization. Also, if there is more than one synchronization method in the object, when a thread is executed with one of the synchronized methods in the object, the other synchronization methods in the object do not allow other threads to execute. But another object generated by the class that this object belongs to P2 can invoke the method that was added to the Synchronized keyword arbitrarily.

The example code above is equivalent to the following code:

public void Method ()  {  
  synchronized (this)   
  {  
    //...  
  }  

This is a P1 object lock, which got the P1 object lock thread, can invoke the P1 synchronization method, and for P2, P1 this lock and he has nothing to do, the program may also in this case get rid of synchronization mechanism control, resulting in data chaos.

2. Sync block, sample code as follows:

public void Method () { 
synchronized (this) 
{ 
//... 
} 

At this point, the lock is so this object, each object corresponds to a unique lock, so which thread to get the object lock who can run the code he controlled. When there is a clear object as a lock, it can write the program, but when there is no clear object as a lock, just want to let a piece of code synchronized, can create a special instance variable (he must be an object) to act as a lock:

 Private byte[] lock = new Byte[0]; 
  public void Method () {  
      synchronized (lock) 
      { 
        // 
      }
  }  

Note: A 0-length byte array object is created more economically than any object--view compiled bytecode: A 0-length byte[] object takes only 3 opcode, while object lock = new Object () requires 7 rows of opcode.

3. The synchronized is applied to the static function, and the sample code is as follows:

Class Foo  
{public  
  synchronized static void Method1 ()  

  {  
    //.  
  }  
  public void Method2 ()  
  {  
    synchronized (foo.class)  
    //
  }  

Both of these synchronization methods call the class lock (class, which is not a specific object produced by this class) of the class to which the object of this method belongs. The
can infer that if a class defines a synchronized static function A and also defines a synchronized instance function B, then the same object obj of this class accesses A and B two methods, respectively, in multiple threads. Do not constitute synchronization because their locks are not the same. The lock of a method is the class that obj belongs to, and the lock of B is the object that obj belongs to.

Related Article

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.