Java Multithreading-Synchronization block instance explanation _java

Source: Internet
Author: User

Java Multithreading-Sync block

Java synchronization blocks (synchronized block) are used to mark methods or blocks of code are synchronized. Java synchronization blocks are used to avoid competition. This article describes the following:

    1. Java synchronization Keywords (synchronzied)
    2. Instance method synchronization
    3. static method Synchronization
    4. Synchronization blocks in instance methods
    5. Synchronization blocks in static methods
    6. Java Synchronization Sample

Java synchronization Keywords (synchronized)

The synchronization blocks in Java are marked with synchronized. Synchronized blocks are synchronized on an object in Java. All synchronized blocks synchronized on one object can only be entered by one thread at a time and perform operations. All other threads waiting to enter the synchronization block will be blocked until the thread in the synchronization block exits.

There are four different kinds of synchronization blocks:

    1. Instance method
    2. static method
    3. Synchronization blocks in instance methods
    4. A synchronized block in a static method

The synchronized blocks are synchronized on different objects. The actual need for that kind of sync block depends on the specific situation.

Instance method synchronization

The following is an instance method of synchronization:

 Public synchronized void Add (int value) {
This.count + = value;
 }

static method Synchronization

static method synchronization and instance method synchronization methods also use the Synchronized keyword. The Java static method synchronizes the following example:

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

Again, here the Synchronized keyword tells Java that the method is synchronized.

The synchronization of a static method is the synchronization of the class object on which the method resides. Because a class can only correspond to one class object in a Java virtual machine, only one thread is allowed to perform static synchronization methods in the same class at the same time.

For static synchronization methods in different classes, a thread can perform static synchronization methods in each class without waiting. A class can be executed by only one thread at a time, regardless of which static synchronization method in the class is invoked.

Synchronization blocks in instance methods

Sometimes you don't need to sync the whole method, but it's part of the synchronization method. Java can synchronize parts of a method.

Examples of synchronized blocks in asynchronous Java methods are as follows:

public void Add (int value) {

 synchronized (this) {
  This.count + = value;
 }
 }

The example uses the Java synchronization block builder to mark a piece of code as synchronized. The code is executed in the same way as the synchronization method.

Note the Java synchronization block constructor encloses the object in parentheses. In the example above, "This" is used, which is the instance itself that calls the Add method. Objects enclosed in parentheses in the synchronization builder are called Monitor objects. The code above uses a monitor object to synchronize, and the synchronization instance method uses an instance of the calling method itself as the monitor object.

Only one thread at a time can be executed within a Java method that synchronizes with the same monitor object.

The following two examples are synchronized on the instance objects they call, so they are equivalent in the execution effect of the synchronization.

 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 example above, only one thread can execute within any one of the two synchronization blocks at a time.

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

A synchronized block in a static method

Similar to the above, here are two examples of static method synchronization. These methods are synchronized on 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 are not allowed to be accessed by the thread at the same time.

If the second synchronization block is not synchronized on the Myclass.class object. Then the two methods can be accessed by the thread at the same time.

Java Synchronization Instance

In the following example, two threads are started, and the Add method Counter one instance is invoked. Because synchronization is on 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 = 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 were created. Their constructors refer to the same Counter instance. The Counter.add method is synchronized on the instance because the Add method is an instance method and is tagged with the synchronized keyword. Therefore, only one thread is allowed to call the method at a time. Another thread must wait until the first thread exits the Add () method to continue executing the method.

If two threads refer to two different Counter instances, they can call the Add () method at the same time. These methods call different objects, so they are synchronized on 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 these two threads, Threada and threadb, no longer reference the same counter instance. The Add method for Countera and Counterb is synchronized on the object to which they belong. Calling the Countera Add method will not block the Add method that calls Counterb.

The above is the Java multithreaded synchronized block of knowledge to explain, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.