Synchronized block synchronization method for Java multithreaded programming _java

Source: Internet
Author: User
Tags object object

The article shares 4 examples of detailed explanations of synchronized

1, whether to add synchronized keyword difference

public class ThreadTest {public

  static void Main (string[] args) {
    Example Example = new Example ();

    Thread T1 = new Thread1 (example);
    Thread t2 = new Thread1 (example);
    T1.start ();
    T2.start ();
  }

Class Example {public
  synchronized void Excute () {for
    (int i = 0; i < 5; ++i) {
      try {
        Thread.slee P (1000);
      } catch (Interruptedexception e) {
        e.printstacktrace ();
      }
      System.out.println ("Excute:" + i);
    }

}} Class Thread1 extends Thread {
  private Example Example;

  Public Thread1 (Example Example) {
    this.example = Example;
  }

  @Override public
  Void Run () {
    example.excute ();
  }
}

Add the Synchronized keyword output as follows

Will output a group of 0-4, then output the next set, two threads to execute sequentially

excute:0
Excute:1
Excute:2
Excute:3
Excute:4
excute:0
Excute:1
Excute:2
Excute:3
Excute:4

The output of the Synchronized keyword is as follows

Two threads execute the Excute method at the same time, concurrent

excute:0
excute:0
Excute:1
Excute:1
Excute:2
Excute:2
Excute:3
Excute:3
Excute:4
Excute:4

2, multiple methods of multithreading situation

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 Excute () {for (int i = 0; i < 5; ++i) {try {Thread
      . Sleep (1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("Excute:" + i);
      } synchronized void Excute1 () {for (int i = 0; i < 5; ++i) {try {thread.sleep (1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("excute1:" + i);

  }} class Thread1 extends Thread {private Example Example;
  Public Thread1 (Example Example) {this.example = Example;
  @Override public void Run () {example.excute ();

  } class Thread2 extends Thread {private Example Example; Public Thread2(Example Example)
  {this.example = example;
  @Override public void Run () {example.excute1 ();

 }
}

Implementation results are as follows

The same is done sequentially, executing one thread and then executing another thread

excute:0
Excute:1
Excute:2
Excute:3
Excute:4
excute1:0
Excute1:1
Excute1:2
Excute1:3
Excute1:4

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, 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.

public class ThreadTest {public static void main (string[] args) {Example Example = new Example ();
    Example example2 = new Example ();
    Thread T1 = new Thread1 (example);
    Thread t2 = new Thread2 (example2);
    T1.start ();
  T2.start ();
        } class Example {public synchronized static void Excute () {for (int i = 0; i < 5; ++i) {try {
      Thread.Sleep (1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("Excute:" + i); } synchronized static void Excute1 () {for (int i = 0; i < 5; ++i) {try {thread.sleep (
      1000);
      catch (Interruptedexception e) {e.printstacktrace ();
    } System.out.println ("excute1:" + i);

  }} class Thread1 extends Thread {private Example Example;
  Public Thread1 (Example Example) {this.example = Example;
  @Override public void Run () {example.excute (); } class Thread2 extends THread {private Example Example;
  Public Thread2 (Example Example) {this.example = Example;
  @Override public void Run () {example.excute1 ();

 }
}

Implementation results are as follows

excute:0
Excute:1
Excute:2
Excute:3
Excute:4
excute1:0
Excute1:1
Excute1:2
Excute1:3
Excute1:4

If there are no static modifiers, two threads pass in different objects, and concurrently execute the

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 (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 you to specify the lock object yourself.

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 void Excute () {synchronized (.) {for (int i = 0; i < 5; ++i) {try
        {thread.sleep (1000);
        catch (Interruptedexception e) {e.printstacktrace ();
      } System.out.println ("Excute:" + i);
          }} public void Excute1 () {synchronized (.) {for (int i = 0; i < 5; ++i) {try {
        Thread.Sleep (1000);
        catch (Interruptedexception e) {e.printstacktrace ();
      } System.out.println ("excute1:" + i);

  Class Thread1 extends Thread {private Example Example;
  Public Thread1 (Example Example) {this.example = Example;
  @Override public void Run () {example.excute (); }
Class Thread2 extends Thread {private Example Example;
  Public Thread2 (Example Example) {this.example = Example;
  @Override public void Run () {example.excute1 ();

 }
}

Implementation results are as follows

excute:0
Excute:1
Excute:2
Excute:3
Excute:4
excute1:0
Excute1:1
Excute1:2
Excute1:3
Excute1:4

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).

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.

The above is about Java multithreaded programming synchronized block synchronization method, I hope to help you learn.

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.