Java Multithreading synchronized keyword detailed explanation (vi) _java

Source: Internet
Author: User
Tags object object thread class

The Synchronized keyword, which represents a lock on this method, is equivalent to whichever thread (such as thread A) is running to this method, checking that there are other threads B (or C, D, etc.) using this method (or other synchronization methods of the Class). You have to wait. Thread B (or C, D) that is using the Synchronized method runs this method before running this thread A, if not, locks the caller, and then runs directly. It consists of two usages: Synchronized method and synchronized block.

Multi-threaded synchronization mechanisms lock resources so that at the same time, only one thread can operate, synchronizing the problems that may occur when multiple threads are simultaneously accessed.

The synchronization mechanism can be implemented using the SYNCHRONIZED keyword.

When the Synchronized keyword modifies a method, the method is called a synchronization method.

Locks are automatically released when the Synchronized method finishes or an exception occurs.

The following is an example to parse the usage of the Synchronized keyword.

1. Use the Synchronized keyword differently

Example Program 1

public class ThreadTest
{public
static void Main (string[] args)
{
Example Example = new E      Xample ();
Thread T1 = new Thread1 (example);
Thread t2 = new Thread1 (example);
T1.start ();
T2.start ();
}
class Example
{public
synchronized void execute ()
{for
(int i = 0; I < 10;        ++i)
{
try
{
thread.sleep);
catch (interruptedexception e)
{
e.printstacktrace ();
}
System.out.println ("Hello:" + i);
}}    Class Thread1 extends Thread
{
private Example Example;
Public Thread1 (Example Example)
{
this.example = Example;
@Override public
Void Run ()
{
example.execute ();
}
}

If you add the Synchronized keyword before the Execute () method, the example program will perform a very different result.

If the Synchronized keyword is not added, two threads execute the Execute () method concurrently, and the output is two sets of concurrency.

If you add the Synchronized keyword, you will output a group of 0 to 9 before outputting the next group, indicating that two threads are executed sequentially.

2. Multithreading of multiple methods

Change the program and add a Method Execute2 () to the example class.

Then write a thread class thread2,thread2 the Run () method executes the Execute2 (). The two methods in the example class are decorated by the synchronized keyword.

Example Program 2

 public class ThreadTest {public static void main (string[] args) {Example Example = new Example ();
    Thread T1 = new Thread1 (example);
    Thread t2 = new Thread2 (example);
    T1.start ();
  T2.start ();
        Class Example {public synchronized void execute () {A for (int i = 0; i < ++i) {try {
      Thread.Sleep ((Long) math.random () * 1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("Hello:" + i); } public synchronized void Execute2 () {for (int i = 0; i < ++i) {try {Thread
      . Sleep ((long) math.random () * 1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("World:" + i);
  }} class Thread1 extends Thread {private Example Example;
  Public Thread1 (Example Example) {this.example = Example; @Override public void Run () {ExaMple.execute ();
  } class Thread2 extends Thread {private Example Example;
  Public Thread2 (Example Example) {this.example = Example;
  @Override public void Run () {example.execute2 (); }
}

If the synchronized keyword is removed, two methods are executed concurrently without affecting each other.

But as the example program says, even two methods:

The execution result is always to execute the output of one thread and then execute another thread.

Description

If an object has multiple synchronized methods, and a thread has entered a synchronized method at some point, the other thread cannot access any of the synchronized methods of the object until the method has finished executing.

Conclusion:

When the Synchronized keyword modifies a method, the method is called a synchronization method.

Each object in Java has a lock (lock), or monitor, that locks the object when a thread accesses the synchronized method of an object. No other thread can access the object's Synchronized method (this refers to all synchronization methods, not just the same method) until the previous thread executes the method (or throws an exception) to release the object's lock. It is possible for other threads to access the Synchronized method of the object again.

Note that this is the time to lock the object, if it is a different object, there is no restriction between the objects.

When you try to construct a second thread object in your code and pass in a new example object, there is no constraint between the execution of two threads.

3. Consider the static synchronization method

When a synchronized keyword-modified method is also statically decorated, it is said that a non-static synchronization method locks the object, but that the static method does not belong to the object but belongs to the class, which locks the class object of the classes in which the method is located.

A class, regardless of how many objects are generated, corresponds to the same class object.

Example Program 3

 public class ThreadTest {public static void main (string[] args) {Example Example = new Example ();
    Thread T1 = new Thread1 (example);
    Static method synchronization does not allow multiple threads to execute example = new example () at the same time, even if a different object is passed in.
    Thread t2 = new Thread2 (example);
    T1.start ();
  T2.start ();
      } class Example {public synchronized static void execute () {for (int i = 0; i < ++i) {try
      {Thread.Sleep ((long) math.random () * 1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("Hello:" + i);
        } synchronized static void Execute2 () {for (int i = 0; i < ++i) {try {
      Thread.Sleep ((Long) math.random () * 1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("World:" + i);
  }} class Thread1 extends Thread {private Example Example; Public Thread1 (Example ExamplE) {this.example = example;
  @Override public void Run () {example.execute ();
  } class Thread2 extends Thread {private Example Example;
  Public Thread2 (Example Example) {this.example = Example;
  @Override public void Run () {example.execute2 ();

 }
}

So if it's a static method (execute () and Execute2 () with the static keyword), even if you pass in a different example object to two threads, the two threads are still mutually restricted, and you must finish one before executing the next.

Conclusion:

If a synchronized method is static, when the thread accesses the method, it locks not the object that the synchronized method is in, but the class object that corresponds to the synchronized method. In Java, no matter how many objects a class has, these objects correspond to a single class object, so that when a thread accesses the two static,synchronized methods of the two objects of the same class, their order of execution is sequential, which means that a thread first executes the method, Another thread does not start until execution completes.

4. Synchronized block

Synchronized block notation:

Synchronized (object)
{   
}

Indicates that the object is locked by the thread while it is executing. (Note that this object can be an object of any class, or you can use the This keyword).

This allows the locking object to be set by itself.

Example Program 4

 public class ThreadTest {public static void main (string[] args) {Example Example = new Example ();
    Thread T1 = new Thread1 (example);
    Thread t2 = new Thread2 (example);
    T1.start ();
  T2.start ();
  } class Example {Private object = new Object ();
        public void execute () {synchronized (object) {i = 0; i < ++i) {try
        {Thread.Sleep ((long) math.random () * 1000);
        catch (Interruptedexception e) {e.printstacktrace ();
      } System.out.println ("Hello:" + i);
        }} public void Execute2 () {synchronized (object) {for (int i = 0; i < ++i) {
        try {thread.sleep (long) math.random () * 1000);
        catch (Interruptedexception e) {e.printstacktrace ();
      } System.out.println ("World:" + i);
  Class Thread1 extends Thread {Private Example Example;
  Public Thread1 (Example Example) {this.example = Example;
  @Override public void Run () {example.execute ();
  } class Thread2 extends Thread {private Example Example;
  Public Thread2 (Example Example) {this.example = Example;
  @Override public void Run () {example.execute2 ();  }
}

Example program 4 achieves the same effect as example program 2, is to make two threads in the order of execution, rather than concurrent, when one thread executes, lock object object, another thread can not execute the corresponding block.

The Synchronized method is actually equivalent to wrapping all the statements in a method with a synchronized block and passing the This keyword in parentheses in the synchronized block. Of course, if it is a static method, it is a class object that needs to be locked.

It is possible that only a few lines of code in a method involve thread synchronization issues, so the synchronized block controls more granular access than the Synchronized method, and only the content in the synchronized block can be accessed by multiple threads at the same time. The other statements in the method can still be accessed by multiple threads at the same time (including before and after the synchronized block).

  Note: The data protected by the synchronized should be private.

Conclusion:

The Synchronized method is a coarse-grained concurrency control, in which only one thread executes the synchronized method at a time;

A synchronized block is a fine-grained concurrency control that only synchronizes code in a block, and other code within the method, outside the synchronized block, can be accessed concurrently by multiple threads.

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.