Java multithreading-thread synchronization and locking problems _java

Source: Internet
Author: User

First, the synchronization problem proposed

Thread synchronization is the destruction of data that prevents multiple threads from accessing a data object.

For example: Two threads Threada, threadb both manipulate the same object Foo object and modify the data on the Foo object.

Package cn.thread;

public class Foo {
  private int x = m;

  public int GetX () {return
    x;
  }

  public int fix (int y) {
    x = XY;
    return x;
  }
}

Package cn.thread;

public class Myrunnable implements Runnable {
  private foo foo = new Foo ();

  public static void Main (string[] args) {
    myrunnable run = new myrunnable ();
    Thread ta = new Thread (Run, "thread-a");
    Thread TB = new Thread (Run, "Thread-b");
    Ta.start ();
    Tb.start ();
  }

  public void Run () {for
    (int i = 0; i < 3; i++) {
      this.fix);
      try {
        thread.sleep (1);
      } catch (Interruptedexception e) {
        e.printstacktrace ();
      }
      System.out.println (Thread.CurrentThread (). GetName () + ": x value of current Foo object =" + Foo.getx ());
    }

  public int fix (int y) {return
    foo.fix (y);
  }

}

Run Result:

Thread-b: x value of current Foo object = 40
THREAD-A: x value of current Foo object = 40
Thread-b: The x value of the current Foo object =-20
THREAD-A: The x value of the current Foo object =-20
Thread-b: The x value of the current Foo object =-80
THREAD-A: The x value of the current Foo object =-80

It is found from the result that such output value is obviously unreasonable. The reason is that two threads have uncontrolled access to the Foo object and modify its data.

If you want to keep the results reasonable, you need only one goal to limit access to Foo, which can only be accessed by one thread at a time. This will ensure the rationality of the data in the Foo object.

There are two things you need to do in a specific Java code:

The resource class Foo variable x is identified as private by the competition access;

Synchronize the code that modifies the variable, using the Synchronized keyword to synchronize the method or code.

Package cn.thread;

public class Foo2 {
  private int x = m;

  public int GetX () {return
    x;
  }

  Sync method public
  synchronized int fix (int y) {
    x = XY;
    SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "run over, decrease" "+ y
        +" ", the current value is:" + x);
    return x;
  }  //Sync code block
//public  int fix (int y) {
//    synchronized (this) {
//      x = XY;      System.out.println ("Thread" +thread.currentthread (). GetName () + "run over, decrease" "+ y
//          +" ", the current value is:" + x);
}////return    x;
//  }

}
Package cn.thread;

public class MyRunnable2 {public

  static void Main (string[] args) {
    MyRunnable2 run = new MyRunnable2 ();
    Foo2 foo2=new Foo2 ();
    
    Mythread T1 = run.new mythread ("Thread A", Foo2, ten);
    Mythread t2 = run.new Mythread ("Thread B", Foo2,-2);
    mythread t3 = run.new mythread ("Thread C", Foo2,-3);
    mythread T4 = run.new mythread ("Thread D", Foo2, 5);
    
    T1.start ();
    T2.start ();
    T3.start ();
    T4.start ();
  }
  
  Class Mythread extends Thread {
    private Foo2 foo2;
    /** Current Value *
    /private int y = 0;
    
    Mythread (String name, Foo2 foo2, int y) {
      super (name);
      This.foo2 = Foo2;
      This.y = y;
    }

    public void Run () {
      foo2.fix (y);}}}



Thread A runs at the end, reducing "10", the current value is: 90
Thread C run end, reduce "-3", current value is: 93
Thread B run end, reduce "-2", the current value is: 95
Thread thread D run over, reduce "5", the current value is: 90

Second, synchronization and locking

1, the principle of the lock

Each object in Java has a built-in lock.

When the program runs to a non-static synchronized synchronization method, it automatically obtains the lock associated with the current instance of the code class being executed (this instance). Getting a lock on an object is also known as acquiring a lock, locking an object, locking on an object, or synchronizing on an object.

The object lock works when the program runs to the synchronized synchronization method or code block.

One object has only one lock. So, if a thread gets the lock, no other thread can get the lock until the first thread releases (or returns) the lock. This also means that no other thread can enter the synchronized method or block of code on the object until the lock is released.

A release lock is a lock thread that exits the synchronized synchronization method or code block.

For locks and synchronizations, there are a few key points:

1), only synchronized methods, and can not synchronize variables and classes;

2, each object has only one lock; when it comes to synchronization, what should be clearly synchronized? In other words, which object is synchronized on?

3, you do not have to synchronize all the methods in the class, the class can have both synchronous and asynchronous methods.

4 If two threads are to execute the synchronized method in a class, and two threads use the same instance to invoke the method, only one thread at a time can execute the method, and the other will wait until the lock is released. In other words: If a thread obtains a lock on an object, no other thread can enter any of the synchronization methods in the class (the object).

5. If the thread has synchronous and asynchronous methods, the asynchronous method can be freely accessed by multiple threads without the restriction of the lock.

6), when the thread sleeps, any locks it holds are not released.

7), the thread can obtain multiple locks. For example, a synchronization method of another object is invoked within the synchronization method of an object, and a synchronous lock of two objects is obtained.

8, synchronization damage concurrency, should be as narrow as possible synchronization range. Synchronization allows you to synchronize not only the entire method, but also part of the code block in the method.

9. When using the Sync code block, you should specify which object to synchronize on, that is, which object to get the lock. For example:

public int fix (int y) {
   synchronized (this) {
      x = xy;
   }
   return x;
}

Of course, the synchronization method can also be rewritten as an asynchronous method, but the functionality is identical, for example:

public synchronized int GetX () {return
   x + +;
}

And

public int GetX () {
   synchronized (a) {return
      x + +;
   }
}

The effect is exactly the same.

Third, static method synchronization

To synchronize a static method, you need a lock for the entire class object, which is the Class (Xxx.class).

For example:

public static synchronized int SetName (String name) {
   xxx.name = name;
}


Equivalent to

public static int SetName (String name) {
   synchronized (xxx.class) {
      xxx.name = name;
   }
}

Four, what if the thread can't get the lock?

If a thread attempts to enter the synchronization method and its lock is already occupied, the thread is blocked on the object. Essentially, a thread enters a pool of that object, where it must wait until its lock is freed and the thread becomes operational or run again.

When considering blocking, be sure to note which object is being used for the lock:

1. A thread that calls a Non-static synchronization method of the same object blocks each other. If they are different objects, each thread has its own lock of objects, and the threads do not interfere with each other.

2. Threads that invoke static synchronization methods in the same class block each other, both of which are locked on the same class object.

3. Static synchronization methods and Non-static synchronization methods will never block each other because static methods are locked on class objects, and Non-static methods are locked on objects of that class.

4. For synchronized code blocks, see what objects have been used for locking (synchronized the contents of the back brackets). Threads that synchronize on the same object block each other, and threads that are locked on different objects will never block each other.

V. When to synchronize

When multiple threads access mutually exclusive (exchangeable) data at the same time, you should synchronize to protect the data, ensuring that two threads do not modify it at the same time.

Non-static methods are typically used for data that can be changed in non-static fields.

Static method access is typically used for data that can be changed in static fields.

If you need to use a static field in a Non-static method, or if you call a Non-static method in a static field, the problem becomes very complex. It has gone beyond the SJCP examination range.

Vi. Thread-Safe classes

This class is called "Thread-safe" when a class is already well synchronized to protect its data.

Even thread-safe classes should be particularly cautious because the threads of operation are still not necessarily secure.

Seven, thread synchronization summary

1, the purpose of thread synchronization is to protect the resource when multiple threads access a resource.

2, the thread synchronization method is implemented by the lock, each object has a cut only a lock, this lock is associated with a specific object, once the thread acquires the object lock, other access to the object's thread can no longer access the object's other synchronization methods.

3, for the static synchronization method, the lock is for this class, the lock object is the class object. The locking of static and Non-static methods does not interfere with each other. A thread acquires the lock and acquires the two object locks when accessing the synchronization method on another object in one of the synchronization methods.

4, for synchronization, it is crucial to be aware of which object is synchronized at all times.

5. Writing thread-safe classes requires constant attention to making the right judgments about the logic and security of competing access resources for multiple threads, analyzing "atomic" operations, and ensuring that other threads do not have access to competing resources during atomic operations.

6. When multiple threads wait for an object lock, a thread that does not acquire the lock will block.

7, deadlock is between the threads waiting for the lock caused by each other, in fact, the probability of occurrence is very small. Really let you write a deadlock program, not necessarily good, hehe. However, once the program has a deadlock, the program will die.

Original link: http://www.cnblogs.com/linjiqin/p/3208843.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.