Java multithreaded programming synchronized keyword detailed _java

Source: Internet
Author: User
Tags instance method

This article introduces some knowledge points of the Synchronized keyword in Java multithreading as Object lock.

The so-called object lock, is synchronized to an object lock. About Object locks refer to: This article

First, analysis

Synchronized can be decorated with instance methods, as follows:

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

Here, thesynchronized keyword locks the current object. This is also known as the reason for object locking.

Why lock the current object? Because MethodA () is an instance method, to perform MethodA (), you need to invoke the form of an object. Method () (Obj.methoda (), obj is an object of the MyObject class, and synchronized is to lock the object of obj.

The code above can also be written like this:

public class MyObject {public

  void MethodA () {
    synchronized (this) {
      //do something ...
    }
  }
 

Second, characteristics

One obvious feature of using the Synchronized keyword synchronization is that when multiple threads have objects of the same MyObject class that are defined in the MyObject class with multiple synchronized adornments, these methods can only be executed in a synchronized manner. That is, after performing a synchronized-modified method, you can perform another synchronized-modified method.

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;
Omitting the construction method
  @Override public
  void Run () {
    super.run ();
    Object.methoda ();
  }


Thread A executes MethodA ()

public class Threadb extends Thread {

  private MyObject object;
Omitting the construction method
  @Override public
  void Run () {
    super.run ();
    Object.methodb ();
  }


Thread B execution MethodB ()

public class Run {public
  static void Main (string[] args) {
    MyObject object = new MyObject ();

    Thread A and thread B hold the same object: Object
    Threada a = new Threada (object);
    THREADB B = new Threadb (object);
    A.start ();
    B.start ();
  }


Because thread A and thread B hold object objects of the same MyObject class, although the two threads need to invoke different methods, they must be synchronized, for example: thread B needs to wait for thread A to execute the MethodA () method before it executes the MethodB () method.

Third, the conclusion

As you can see from the above, the scope of the synchronized lock described in this article is the entire object. If a class has multiple synchronized-decorated synchronization methods, and multiple threads hold the same object of the class (the same object for that class), the execution of each method is synchronized even though they invoke different methods.

If there is no shared variable between the methods of each synchronization, or if there is no connection between each method, it can only be performed synchronously, which can affect efficiency.

Application--use synchronized to avoid data inconsistency caused by reading dirty data

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 user name and password. in reality, a username corresponds to a password.

MethodB () is responsible for reading user names and passwords.

If MethodB () is not decorated with synchronized, thread A changes the username by calling MethodA () on line 7th, and then discards the CPU for some reason (such as sleeping in line 9th).

At this point, if thread B executes MethodB (), the user name read is the user name ("a") that thread A has changed, but the password is the original password ("BB"). Because thread A is asleep, there's no time to change the password.

However, if MethodB () is decorated with synchronized, then thread B can only perform METHODB read the user name and password after thread A has finished executing (that is, changing the username and changing the password). Therefore, the problem of dirty reading caused by the inconsistency of data is avoided.

The above is the entire content of this article, I hope to learn Java program to help you.

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.