Home  >  Article  >  Java  >  Detailed explanation of the Synchronized keyword in java multi-thread programming

Detailed explanation of the Synchronized keyword in java multi-thread programming

高洛峰
高洛峰Original
2017-01-05 14:43:381486browse

This article introduces some knowledge points about the synchronized keyword in JAVA multi-threading as an object lock.

The so-called object lock is synchronized locking an object. Regarding object locks, please refer to: this article

1. Analysis

synchronized can modify instance methods in the following form:

public class MyObject {
  synchronized public void methodA() {
    //do something....
  }

Here, the synchronized keyword locks the current object. This is also why it is called an object lock.

Why lock the current object? Because methodA() is an instance method, if you want to execute methodA(), you need to call it in the form of object.method() (obj.methodA(). obj is an object of the MyObject class. Synchronized locks the obj object. ).

The above code can also be written like this:

public class MyObject {
 
  public void methodA() {
    synchronized(this){
      //do something....
    }
  }

2. Features

Use the synchronized keyword to synchronize an obvious feature Yes: When multiple synchronized instance methods are defined in the MyObject class, if multiple threads own the same object of the MyObject class, these methods can only be executed in a synchronous manner. That is, after executing a synchronized modified method, another synchronized modified method can be executed.

As follows:

public class MyObject {
 
  synchronized public void methodA() {
    //do something....
  }
 
  synchronized public void methodB() {
    //do some other thing
  }
}

There are two synchronized modified methods in the MyObject class.

public class ThreadA extends Thread {
 
  private MyObject object;
//省略构造方法
  @Override
  public void run() {
    super.run();
    object.methodA();
  }
}

Thread A executes methodA()

public class ThreadB extends Thread {
 
  private MyObject object;
//省略构造方法
  @Override
  public void run() {
    super.run();
    object.methodB();
  }
}

Thread B executes methodB()

public class Run {
  public static void main(String[] args) {
    MyObject object = new MyObject();
 
    //线程A与线程B 持有的是同一个对象:object
    ThreadA a = new ThreadA(object);
    ThreadB b = new ThreadB(object);
    a.start();
    b.start();
  }
}

Since thread A and thread B hold the same MyObject class object, although the two threads need to call different methods, they must be synchronized For example: Thread B needs to wait for thread A to finish executing methodA() method before it can execute methodB() method.

3. Conclusion

As can be seen from the above, the scope of the synchronized lock described in this article is the entire object. If there are multiple synchronized modified synchronization methods in a class, and multiple threads hold the same object of the class (the same object of the class), even though they call different methods, the execution of each method is also synchronized.

If there are no shared variables between the synchronized methods, or there is no connection between the various methods, but they can only be executed synchronously, this will affect efficiency.

4. Application - Use synchronized to avoid reading dirty data due to data inconsistency

The following example:

public class MyObject {
 
  private String userName = "b";
  private String passWord = "bb";
   
  synchronized public void methodA(String userName, String passWord) {
    this.userName = userName;
    try{
      Thread.sleep(5000);
    }catch(InterruptedException e){
       
    }
    this.passWord = passWord;
  }
 
  synchronized public void methodB() {
    System.out.println("userName" + userName + ": " + "passWord" + passWord);
  }
}

methodA() is responsible for changing the username and password. In reality, a username corresponds to a password.

methodB() is responsible for reading the username and password.

If methodB() is not modified with synchronized, thread A calls methodA() and executes to line 7, changes the user name, and gives up the CPU for some reason (such as sleeping on line 9).

At this time, if thread B executes methodB(), the user name read is the user name changed by thread A ("a"), but the password is the original password ("bb" ). Because thread A went to sleep and did not have time to change the password.

However, if methodB() is modified with synchronized, then thread B can only wait for thread A to complete execution (that is, change the user name and password) before executing method B to read the user name and password. Therefore, dirty read problems caused by data inconsistency are avoided.

The above is the entire content of this article. I hope it will be helpful to everyone learning java programming.

For more detailed explanations of the Synchronized keyword in java multi-threaded programming, please pay attention to the PHP Chinese website!

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