Home  >  Article  >  Java  >  Detailed example code introduction to Java synchronization code block

Detailed example code introduction to Java synchronization code block

黄舟
黄舟Original
2017-02-28 10:47:182257browse

A Java synchronized block makes a method or block of code synchronized. Java synchronized blocks can be used to avoid static conditions.

This Java synchronization keyword

Synchronized blocks in Java are marked by using the synchronized keyword. A synchronized block in Java is synchronized on some objects. All synchronized blocks synchronized on all objects can only be executed by one thread at the same time. All other threads trying to enter the synchronized block are blocked until the thread inside the synchronized block leaves the block.

The synchronized keyword can be used to mark four different types of blocks:


  1. Instance method

  2. Static method

  3. Code block in instance method

  4. Code block in static method

These blocks are synchronized in different objects. Which sync block type you need depends on the specific scenario.

Synchronized instance methods

Here is an example:

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

Note the use of the synchronized keyword in the method life . This tells Java that this method is synchronized.

A synchronized instance method in Java is synchronized on the instance object belonging to this method. Therefore, each instance has its synchronization method synchronized on a different object: its own instance. Only one thread can execute an instance synchronized method, and then one thread can execute a synchronized instance method one at a time. One thread per instance.

Synchronized static methods

Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is an example:

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

There is also a synchronized keyword here to tell Java that this method is synchronized.

Synchronized static methods are synchronized on the class object of the class to which the static method belongs. Because only one class object exists for each class in the Java virtual machine, only one thread can execute a synchronized static method of the same class.

If this static synchronization method is located in different classes, then a thread can execute the internal static synchronization method of each class. Threads of each class no matter which static synchronization method they call.

Synchronized blocks in instance methods

You cannot synchronize the entire method. Sometimes it is better to synchronize parts of a method. Java synchronized blocks inside methods make this possible.

Here is an example:


  public void add(int value){

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

This example uses Java synchronization blocks to build a code block that is synchronized. If it is a synchronous method, this method will be executed.

Note how this Java synchronization block is constructed with parts of an object. In this example, "this" is used, which is the instance of the add method that is called. The object in the accepting brackets constructed through synchronization is called a monitor object. This code assumes that the monitor object will be synchronous. A synchronized instance method uses the object it belongs to as the watch object.

Only one thread can execute in a Java synchronized block of the same monitored object.

The following two examples are synchronized on the instance they are called. Therefore they are equivalent:


  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);
       }
    }
  }


Therefore only one thread can execute one of the two synchronized blocks in this example.

There is a second synchronization block that is synchronized on a different object for this, and then a thread can only execute one internal method at a time.

Synchronized block in static method

There are two identical instances here as static method. These methods are synchronized in the class object of the class to which this 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);  
       }
    }
  }


Only one thread can execute any of the two methods at the same time.

There is a second synchronization block that is synchronized on a different object. For MyClass.class, then a thread can only execute one internal method at the same time.

Java Synchronization Example

Here is an example, start two threads, and they both call the add method of the same instance of Counter. Only one thread can call the add method of the same instance at a time, because this method is synchronized on the instance it belongs to:

  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. Two identical Counter instances are passed to their constructors. The add method is synchronized on the instance because the add method is an instance method and marked as synchronized. Therefore, only one thread can call this add method at a time. Other threads will wait until the first thread leaves the add method before it can execute.

If two threads reference two separate Counter instances, there will be no problem calling the add method at the same time. This call will be on a different object, so this method call will also be synchronized on a different object (the object that belongs to this method). Therefore this call will not block. Here is an 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(); 
    }
  }

注意这两个线程,他们不再引用相同的实例。counterA和counterB的add方法同步在它们自己的实例上。因此不会堵塞。

Java并发工具

这个synchronized机制是java的第一个途径对于访问同步访问被多线程共享的对象。但是这个synchronized机制不是最高级的。那就是为什么Java 5提供了一个并发工具类的集合去帮助开发者实现更细粒度的并发控制相对于synchronized而言。


 以上就是Java同步代码块的详细实例代码介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn