Java concurrent Programming: synchronization of Threads

Source: Internet
Author: User
Tags instance method

Java concurrent Programming: Synchronization of Threads Table of Contents
    • 1. Synchronized Modification method
    • 2. Synchronized Modifier code block
    • 3. Synchronized modified static method

The synchronization of threads is achieved through locks. Before we use the lock on the concurrent package, we will first understand the Java native synchronization lock. Every object in Java has a lock, which is exclusive. As long as any one by one threads acquire a lock, the other thread can no longer acquire the lock and only block the queue to get the lock on the object.
All operations in Java are implemented through threads, even though we do not actively create threads, but also use the main thread that is automatically created by the process to complete the operation, along with a garbage collection thread created with the process.
The way a thread acquires a lock is obtained by using the synchronized modifier. Synchronized modifiers can be used in several different places, but their role is to get a lock on an object.

1Synchronized Modification method

This use is most common when we do not acquire locks:

 Public class Syncdemo Implements Runnable {    Private int Count= 0;@Override     Public void Run() {count++; System.out.println(Count);}     Public Static void Main(String[] args) {        Syncdemo runnable=New Syncdemo(); for (int I= 0; I < 10; i++) {            Thread Thread=New Thread(Runnable); Thread.Start();}    }}
24356278910

As you can see, the result of the output is completely wrong.
So, let's add synchronized to the front of the method run () and try again:

synchronized  Public void Run (){    count++;    System.out.println(count); }
12345678910

The result is exactly the right one.
So, after synchronized the modified method, you can let the thread get the lock of the object, so that when other threads want to call the function, they need to get the lock of the object first, so as to achieve the purpose of synchronization.

2Synchronized modifying code blocks

The code block is modified to run with the same result as the decorated method:

 Public void Run (){    synchronized(this){        count++;        System.out.println(count);   }}

If you use synchronized (Object) to decorate a block of code, you can play a similar effect to the adornment method. Only the objects here can be other objects, not the current object. This means that you can use this method to obtain the lock of any object, as long as the object can be passed in. At the same time, you can lock only some of the code, only the code that will use the shared resources, such as modifying the object's member variable code, and so on. And the other code is released, equivalent to the other code is running concurrently, only the locked part of the code needs to be queued to run.

3Synchronized modifying the static method

When we use the synchronized modification method, we get the lock of the object, so when we modify the static method, is the lock of the object obtained or not?

 Public class Syncdemo Implements Runnable {    Private Static int Count= 0;synchronized  Public void Instancemethod() {count++; System.out.println("instance:"+ Count);}    synchronized  Public Static void Staticmethod() {count++; System.out.println("Static:"+ Count);}    @Override     Public void Run() {Instancemethod(); Staticmethod();}     Public Static void Main(String[] args) {        Syncdemo runnable=New Syncdemo(); for (int I= 0; I < 10; i++) {            Thread Thread=New Thread(Runnable); Thread.Start();}    }}

We use synchronized to modify the common instance method and the static method respectively, and then run:

Instance:1static:3instance:3static:4instance:5static:6instance:7static:8instance:9static:10instance:11static:1 2instance:13static:14instance:15static:16instance:17static:18instance:19static:20

We find that they are not locked by the same object. So, what objects are locked when the static method is modified? When the static method is decorated, the method of all objects of the class is synchronized, so the lock of the class object is obtained. Each class generates a. class object after the load is complete. Let's use two examples to prove each one.
First, when the static method is decorated, the method for all the objects of the class is synchronous:

 Public void Run() {Staticmethod();} Public Static void Main(String[] args) {     for (int I= 0; I < 10; i++) {        Syncdemo runnable=New Syncdemo();Thread Thread=New Thread(Runnable); Thread.Start();}}
Static:1static:2static:3static:4static:5static:6static:7static:8static:9static:10

Create a different object, and then call the static method of the synchronized adornment, and the result is synchronous.
We then run the code block in the instance method by getting the lock on the. Class object again:

 Public class Syncdemo Implements Runnable {    Private Static int Count= 0; Public void Instancemethod() {        synchronized(Syncdemo.class) {count++; System.out.println("instance:"+ Count);}    }    synchronized  Public Static void Staticmethod() {count++; System.out.println("Static:"+ Count);}    @Override     Public void Run() {Instancemethod(); Staticmethod();}     Public Static void Main(String[] args) {        Syncdemo runnable=New Syncdemo(); for (int I= 0; I < 10; i++) {            Thread Thread=New Thread(Runnable); Thread.Start();}    }}

Note the here:

synchronized (Syncdemo. class ){    count++;    System.out.println("instance:" + count); }
Instance:1instance:2static:3instance:4static:5static:6instance:7static:8instance:9static:10instance:11static:1 2instance:13static:14instance:15static:16instance:17static:18instance:19static:20

As we can see, two methods are executed synchronously, indicating that they are getting the same lock, so when the static method is decorated, it gets a. Class lock. When locking blocks of code, we use This.getclass () and Syncdemo.class are the same.

Date:2017-07-05 21:14

Author:wen YANG

created:2017-07-05 Wed 22:16

Emacs 25.2.1 (ORG mode 8.2.10)

Validate

Java concurrent Programming: synchronization of 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.