Java multithreading-synchronization block and java multithreading Synchronization

Source: Internet
Author: User

Java multithreading-synchronization block and java multithreading Synchronization

The Java synchronization block (synchronized block) is used to mark methods or code blocks that are synchronized. Java synchronization block is used to avoid competition. This article introduces the following:

  • Java synchronization keyword (synchronzied)
  • Instance method Synchronization
  • Static Method Synchronization
  • Synchronization block in instance method
  • Synchronization block in Static Method
  • Java synchronization example
Java synchronization keyword (synchronized)

Synchronization blocks in Java are marked with synchronized. The synchronization block is synchronized to an object in Java. All synchronization blocks synchronized to an object can only be entered and operated by one thread at the same time. All other threads waiting to enter the synchronization block will be blocked until the threads executing the synchronization block exit.

There are four different synchronization blocks:

The above synchronization blocks are synchronized to different objects. The actual synchronization block depends on the actual situation.

Instance method Synchronization

The following is a synchronous instance method:

 public synchronized void add(int value){this.count += value; }
Static Method Synchronization

Static Method synchronization also uses the synchronized keyword like the instance method synchronization method. Java static method synchronization is as follows:

public static synchronized void add(int value){ count += value; }

Similarly, the synchronized keyword tells Java that the method is synchronous.

Static Method synchronization is performed on the class object where the method is located. Because a class in a Java Virtual Machine can only correspond to one class object, only one thread is allowed to execute static Synchronization Methods in the same class at the same time.

For static Synchronization Methods in different classes, a thread can execute static Synchronization Methods in each class without waiting. Regardless of the static synchronization method in the class, a class can only be executed by one thread at the same time.

Synchronization block in the instance method

Sometimes you do not need to synchronize the entire method, but a part of the synchronization method. Java can synchronize some of the methods.

An example of a synchronization block in a non-synchronous Java method is as follows:

public void add(int value){    synchronized(this){       this.count += value;    }  }

In this example, the Java synchronization block constructor is used to mark that a piece of code is synchronized. The code is executed in the same way as the synchronization method.

Note that the Java synchronization block constructor enclose objects with parentheses. In the preceding example, "this" is used to call the instance itself of the add method. The object enclosed in parentheses in the synchronization constructor is called the monitor object. The above Code uses the monitor Object synchronization, and synchronizes the instance method using the instance that calls the method itself as the monitor object.

Only one thread can be executed in the Java method synchronized to the same monitor object at a time.

The following two examples synchronize the instance objects they call, so they are equivalent in the synchronous execution effect.

 public class MyClass {    public synchronized void log1(String msg1, String msg2){       log.writeln(msg1);       log.writeln(msg2);    }    public void log2(String msg1, String msg2){       synchronized(this){          log.writeln(msg1);          log.writeln(msg2);       }    }  }

In the preceding example, only one thread can be executed in any of the two synchronization blocks.

If the second synchronization block is not synchronized to this instance object, the two methods can be executed simultaneously by the thread.

Synchronization block in Static Method

Similar to the above, the following is an example of two static methods for synchronization. These methods are synchronized to the class object to which the method belongs.

public class MyClass {    public static synchronized void log1(String msg1, String msg2){       log.writeln(msg1);       log.writeln(msg2);    }    public static void log2(String msg1, String msg2){       synchronized(MyClass.class){          log.writeln(msg1);          log.writeln(msg2);       }    }  }

These two methods cannot be simultaneously accessed by threads.

If the second synchronization block is not synchronized to the object MyClass. class. The two methods can be simultaneously accessed by the thread.

Java synchronization instance

In the following example, two threads are started and the add method of the same instance of the Counter class is called. Because the method is synchronized to the instance to which the method belongs, only one thread can access the method at the same time.

public class Counter{     long count = 0;     public synchronized void add(long value){       this.count += value;     }  }  public class CounterThread extends Thread{     protected Counter counter = null;     public CounterThread(Counter counter){        this.counter = counter;     }     public void run() {    for(int i=0; i<10; i++){           counter.add(i);        }     }  }  public class Example {    public static void main(String[] args){      Counter counter = new Counter();      Thread  threadA = new CounterThread(counter);      Thread  threadB = new CounterThread(counter);      threadA.start();      threadB.start();    }  }

Two threads are created. Their constructor references the same Counter instance. The Counter. add method is synchronized to the instance because the add method is an instance method and is marked with the synchronized keyword. Therefore, only one thread can call this method at a time. The other thread must wait until the first thread exits the add () method before continuing to execute the method.

If two threads reference two different Counter instances, they can call the add () method at the same time. These methods call different objects, so these methods are synchronized to different objects. These method calls will not be blocked. As shown in the following example:

public class Example {    public static void main(String[] args){      Counter counterA = new Counter();      Counter counterB = new Counter();      Thread  threadA = new CounterThread(counterA);      Thread  threadB = new CounterThread(counterB);      threadA.start();      threadB.start();    }  }

Note that the two threads, threadA and threadB, no longer reference the same counter instance. The add methods of councounter and counterB are synchronized to the objects to which they belong. Calling the counterB add method does not block calling the counterB add method.

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.