Detailed approach to thread synchronization in Java multithreaded programming _java

Source: Internet
Author: User
Tags thread class

1, multithreading synchronization:
1.1, synchronization mechanism:
in multiple threads, there may be multiple threads trying to access a limited resource that must be prevented from happening. So the synchronization mechanism is introduced: when a thread uses a resource, it locks it so that other threads will not be able to access that resource until it is unlocked.

1.2. Examples of shared member variables:
member variables and local variables:
Member Variable:

If a variable is a member variable, then more than one thread operates on the member variable of the same object, which is a shared member variable.

Local variables:

If a variable is a local variable, then multiple threads operate on the same object, and each thread will have a copy of the local variable. The local variables between them do not affect each other.

The following examples illustrate:
Implements the runnable thread class:

Class MyThread3 implements runnable{

 //Two threads manipulate the same object, share member variables
 //int i;
 @Override public
 Void Run () {
  //two threads manipulate the same object, each holding a copy of the local variable
  int i = 0;
  while (i<100) {
   System.out.println (i);
   i++;
   try {
    thread.sleep;
   } catch (Interruptedexception e) {
    e.printstacktrace ()
 }}}
}

Manipulate the same object in the main method with two threads:

public static void Main (string[] args) {

 MyThread3 mythread = new MyThread3 ();
 The following two threads operate on the same object (the Runnable implementation class object) thread thread
 = new Thread (mythread);
 Thread thread2 = new Thread (mythread);
 Each of the local variables to save the copy, no effect, output 200 digital
 thread.start ();
 Thread2.start ();
}

Here, if I become a member variable, then output 100 digits.

1.3. Read errors caused by shared resources
For example, two threads share a number object, get the data through the GetNumber method of the number class, read the data and rewrite it, and find the duplicate read operation:

First create a number class:

Class number{
 private int number = ten;
 Public String getnumber (int i) {
  if (number > 0) {
   try {
    thread.sleep;
   } catch ( Interruptedexception e) {
    e.printstacktrace ();
   }
   Number = i;
   Return "Remove" +i+ "success, Remaining quantity:" +number;
  }
  Return "Remove" +i+ "failed, remaining quantity:" +number
 }
}

A thread class that contains a reference to the number class for a private property in the thread class:

Class MyThread4 extends thread{

 //Two threads manipulate the same object, share member variable number number
 ;
 Public MyThread4 (number number) {
  this.number = number;
 }
 @Override public
 Void Run () {
  System.out.println (Number.getnumber (8));
 }


Create two thread classes in the main function, containing references to instances of the same number class:

public static void Main (string[] args) {Number number

 = new number ();
 Two threads manipulate the same object, the member variable number of the shared object number
 MyThread4 mythread = new MyThread4 (number);
 MyThread4 myThread2 = new MyThread4 (number);
 Mythread.start ();
 Mythread2.start ();
}

Thus, when the first thread reads the number variable in number, it is saved and then dormant for 0.1 seconds, then the second thread then reads the numbers variable and saves it, at which point the two threads hold the same digit, and when modified, the same number is modified two times.

2, the implementation of the synchronization mechanism:

Synchronized has always been a veteran role in multithreaded concurrent programming, and many people call it a heavyweight lock, but as the Java SE1.6 optimizes synchronized, in some cases it's not that heavy.
Each object in Java can be used as a lock.

For synchronization methods, the lock is the current instance object.
For static synchronization methods, the lock is the class object for the current object.
For a synchronized method block, the lock is an object configured in synchonized brackets.
When a thread attempts to access a synchronized code block, it must first get a lock, and must release the lock when exiting or throwing an exception.
2.1, use synchronized keyword to create synchronized method:
using the Synchronized keyword, the method modified by this keyword is called the synchronization method.

Each object in Java has a lock or monitor, and when accessing the Synchronized method of an object, it means locking the object, not just the method.

This way, if an object's synchronized method is executed by a thread, other threads cannot access any of the object's synchronized methods (but other non-synchronized methods can be invoked). Until the synchronized method is finished.

Static Synchronized method invocation case:
When you call an object's static synchronized method, it locks the object that is not the synchronized method, but the class object corresponding to the object synchronized the method. This way, other threads cannot invoke other static synchronized methods of the class, but you can call non-static synchronized methods.

Conclusion: Executes the object of static Synchronized method lock method, executes the class object corresponding to the object of Non-static synchronized method lock method.

The following is an example of a multithreaded call to a static method, because the class object corresponding to the object of the method is locked, and other threads cannot invoke other static synchronized methods on the object that the method is in:

/**
 * Defines a class that contains the method that the thread class needs to invoke/
class compute1{
 //At this point if a thread calls the method,
 // The class object that corresponds to the object of the synchronized method is locked,
 //instead of the object that the synchronized method is anchored to public
 synchronized static void Execute () {
  for (int i = 0; i<100; i++) {
   try {
    thread.sleep ();
   } catch (Interruptedexception e) {
    E.printstacktrace ();
   }
   System.out.println ("compute1:execute1" + i++);
  }
 Public synchronized static void Execute2 () {for
  (int i = 0; i<100; i++) {
   try {
    thread.sleep ()
   } catch (Interruptedexception e) {
    e.printstacktrace ();
   }
   System.out.println ("Compute1:execute2" + i++);
  }
 }

Two threads in the main method call the two static synchronized methods of the same object, respectively:

public static void Main (string[] args) {
 Compute1 com = new Compute1 ();
 Thread thread1 = new Thread1 (COM);
 Thread thread2 = new Thread2 (COM);
 Thread1.start ();
 Thread2.start ();
}

Only one static method can be called at a time until execution completes.

2.2. Create a synchronized code block using synchronized:
by using synchronized to synchronize blocks of code, lock an object that acts as an executable flag to achieve the effect of synchronization:

/**
 * Defines a class that contains the method that the thread class needs to
 invoke
/class compute1{
 //Lock the Object1 object by synchronizing the code block to lock the other same synchronized code block
 Private Object Object1 = new Object ();
 public void Execute () {
  synchronized (object1) {for
   (int i = 0; i<100; i++) {
    try {
     thread.sleep (100) ;
    } catch (Interruptedexception e) {
     e.printstacktrace ();
    }
    System.out.println ("compute1:execute1" + i++);
   }
  }
 Public synchronized void Execute2 () {
  synchronized (object1) {for
   (int i = 0; i<100; i++) {
    try {
     Thread.Sleep (MB);
    catch (Interruptedexception e) {
     e.printstacktrace ();
    }
    System.out.println ("Compute1:execute2" + i++);
   }}}


If you want to use the synchronized synchronized code block to achieve and use the same effect as the Synchronized method, you can lock the This reference:

Synchronized (this) {
 ...
}

2.3, the difference between the Synchronized method and the Synchronized Sync code block:
The Synchronized Sync code block simply locks the code block, and the code outside the code block can be accessed.

The synchronized method is coarse-grained concurrency control, and only one thread at a time can execute the synchronized method.

Synchronized synchronized code blocks are fine-grained concurrency controls that only synchronize code in a block, and code outside the code block can be accessed concurrently by other threads.

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.