Home Java javaTutorial Use of synchronized keyword

Use of synchronized keyword

Sep 06, 2019 pm 04:02 PM
synchronized

The synchronized keyword is a synchronization lock commonly used in Java concurrent programming. It is used to lock methods or code blocks. When locking code blocks, it can be synchronized(this){}, synchronized(Object){}, synchronized(class) {}.

Use of synchronized keyword

#The lock will be automatically released when the locked content is executed or an exception is thrown during execution.

If you want to manually release the lock, you need to call the wait() method of the locked object to release the lock and put it in a waiting state, switch to other threads to run, and the notify() method only wakes up the object that has been called. wait() method of other threads, but the lock will not be released, and the selection order is not controlled by the code and is implemented by the virtual machine.

Therefore, the wait(), notify(), and notifyAll() methods of the object can only be used with the synchronized keyword to complete scheduling between threads.

The locked method is equivalent to synchronized(this){all the code of the method as a code block}, as follows:

1

2

3

public synchronized void test() {

...

}

Copy after login

Equivalent to

1

2

3

4

5

public void test() {

synchronized (this) {

...

}

}

Copy after login

The above example is locked is an object of this class. If a static method is locked, we know that the static method belongs to the class and not to the object. Therefore, the static method modified by synchronized locks all objects of this class, that is, even two Instance objects, as long as they belong to this class, will be locked.

1

2

3

public synchronized static void test() {

    ...

}

Copy after login

Equivalent to

1

2

3

4

5

public static void test() {

synchronized (所在类.class) {

...

}  

}

Copy after login

Whether it is a lock method or a code block, no matter what the reference object is when locking the code block, it is clear as long as you remember one principle, that is, when the reference object Synchronization locks only work when they are the same, otherwise the locks will not be mutually exclusive and can be executed concurrently.

synchronized(this) indicates that the lock takes effect when the object instances of the current class are the same, synchronized(Object) indicates that the lock takes effect when the Object objects are the same, and synchronized(class) indicates that the lock takes effect when they are all of the same class. kick in.

Give a simple example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public class TestController {

  

    public class Task implements Runnable{

        private String str;

         

        Task(String str){

            this.str=str;

        }

         

        @Override

        public void run() {

            synchronized (str) {

                try {

                    Thread.sleep(3000l);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println(str);

            }

        }

         

    }

     

    public static void main(String[] args) throws InterruptedException {

        TestController testController = new TestController();

        Thread thread1 = new Thread(testController.new Task("1"));

        Thread thread2 = new Thread(testController.new Task("1"));

        thread1.start();

        thread2.start();

    }

}

Copy after login

In the above code, the reference object str is "1". In java, if the String string passes this.str="1", Assignment is equivalent to str=String.valueOf("1"). If the string "1" has been initialized before, the previous one will be taken directly, so it is the same object. According to the principle introduced above, the lock will take effect, so the result is that 1 will be output after 3 seconds, and 1 will be output after another 3 seconds.

If thread2 is changed to

1

Thread thread2 = new Thread(testController.new Task("2"));

Copy after login

then one of the reference objects is "1" and the other is "2", which are not the same object, so the lock will not be mutually exclusive, and it will not works, so the result is that 1 and 2 are output almost simultaneously after 3 seconds.

All of the above are multiple threads calling the same method at the same time. What if different methods are called?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

public class Test{

     

    public synchronized void m1(){

        System.out.println("m1 running...");

        try {

            Thread.sleep(3000l);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("m1 end");

    }

     

    public synchronized void m2(){

        System.out.println("m2 running...");

        System.out.println("m2 end");

    }

     

    public static void main(String[] args) {

        Test test = new Test();

        new Thread(new Runnable() {

            @Override

            public void run() {

                test.m1();

            }

        }).start();

        new Thread(new Runnable() {

            @Override

            public void run() {

                test.m2();

            }

        }).start();

    }

     

}

Copy after login

The output result of the above code is:

1

2

3

4

5

m1 running...

//过3秒

m1 end

m2 running...

m2 end

Copy after login

As mentioned above, the synchronized modification is equivalent to synchronized(this){all the code of the method as a code block}, and this represents is an object, that is to say, the first Thread obtains the lock of the test object. Because the objects are all the same test, the second Thread cannot obtain the lock and is blocked.

Change the above example into the following:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

private String str = "1";

     

public void m1(){

    synchronized(str){

        System.out.println("m1 running...");

        try {

            Thread.sleep(3000l);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("m1 end");

    }

}

  

public void m2(){

    synchronized(str){

        System.out.println("m2 running...");

        System.out.println("m2 end");

    }

}

Copy after login

When the first Thread calls m1(), it obtains the lock of the object str, and the second Thread also needs it when it calls m2(). Obtain the lock of the object str, and because they are the same Test object, the two strs are also the same object, so the second Thread will be blocked because it cannot obtain the lock, and the output result is the same as the previous example.

If the above example is transformed into the following:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

public class M1 {

     

    public void m(String str){

        synchronized (str) {

            System.out.println("m1 runing");

            try {

                Thread.sleep(3000l);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            System.out.println("m1 end");

        }

    }

  

}

public class M2 {

     

    public void m(String str){

        synchronized (str) {

            System.out.println("m2 runing");

            System.out.println("m2 end");

        }

    }

  

}

public class Test {

  

    public static void main(String[] args) {

        String str = "1";

        new Thread(new Runnable() {

            @Override

            public void run() {

                new M1().m(str);

            }

        }).start();

        new Thread(new Runnable() {

            @Override

            public void run() {

                new M2().m(str);

            }

        }).start();

    }

     

}

Copy after login

The method called this time is in two classes, but the result is the same as the previous two examples, because the locked They are all str objects passed in. There is only one lock for the same object. If the first Thread takes it, the second Thread can only wait.

Summary:

A. Regardless of whether the synchronized keyword is added to a method or an object, if the object it acts on is non-static, the lock it acquires is the object ; If the object synchronized acts on is a static method or a class, the lock it acquires is for the class, and all objects of the class have the same lock.

B. Each object has only one lock associated with it. Whoever gets this lock can run the code it controls.

C. Achieving synchronization requires a lot of system overhead and may even cause deadlock, so try to avoid unnecessary synchronization control

The above is the detailed content of Use of synchronized keyword. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface Apr 21, 2023 am 08:04 AM

1. Basic features 1. It starts with an optimistic lock, and if lock conflicts are frequent, it is converted to a pessimistic lock. 2. It starts with a lightweight lock implementation, and if the lock is held for a long time, it is converted to a heavyweight lock. 3. The spin lock strategy that is most likely used when implementing lightweight locks 4. It is an unfair lock 5. It is a reentrant lock 6. It is not a read-write lock 2. The JVM will synchronize the locking process Locks are divided into no lock, biased lock, lightweight lock, and heavyweight lock states. It will be upgraded sequentially according to the situation. Biased lock assumes that the male protagonist is a lock and the female protagonist is a thread. If only this thread uses this lock, then the male protagonist and the female protagonist can live happily forever even if they do not get a marriage certificate (avoiding high-cost operations). But the female supporting role appears

Java keyword synchronized principle and lock status example analysis Java keyword synchronized principle and lock status example analysis May 11, 2023 pm 03:25 PM

1. The concept of lock in Java Spin lock: When a thread acquires a lock, if the lock has been acquired by another thread, then the thread will wait in a loop, and then continue to judge whether the lock can be successfully acquired until it is acquired. The lock will exit the loop. Optimistic locking: Assuming there is no conflict, if the data is found to be inconsistent with the previously acquired data when modifying the data, the latest data will be read and the modification will be retried. Pessimistic lock: Assume that concurrency conflicts will occur, synchronize all data-related operations, and start locking from the time the data is read. Exclusive lock (write): Add a write lock to the resource. The thread can modify the resource, but other threads cannot lock it again (single write). Shared lock (read): After adding a read lock to a resource, it can only be read but not modified. Other threads can only add read locks and cannot add write locks (multiple). See as S

How to use synchronized to implement synchronization mechanism in Java? How to use synchronized to implement synchronization mechanism in Java? Apr 22, 2023 pm 02:46 PM

Summary of how to use synchronized in Java 1. When synchronized is used as a function modifier, the sample code is as follows: Publicsynchronizedvoidmethod(){//….} This is the synchronization method. So which object is synchronized locked at this time? What he locks is calling this synchronized method object. In other words, when an object P1 executes this synchronization method in different threads, they will form mutual exclusion to achieve synchronization effect. However, another object P2 generated by the Class to which this object belongs can arbitrarily call this method with the synchronized keyword added. The sample code above, etc.

What are the three synchronization methods in Java and how to use them? What are the three synchronization methods in Java and how to use them? Apr 27, 2023 am 09:34 AM

1. Explain that synchronized is our most commonly used synchronization method, and there are three main ways to use it. 2. Example//General class method synchronization synchronizedpublidvoidinvoke(){}//Class static method synchronization synchronizedpublicstaticvoidinvoke(){}//Code block synchronization synchronized(object){}The difference between these three methods is that the synchronized objects are different. Ordinary classes synchronize the object itself, static methods synchronize the Class itself, and code blocks synchronize the objects we fill in the brackets. What collections are there in Java?

What is the principle and process of Java Synchronized lock upgrade? What is the principle and process of Java Synchronized lock upgrade? Apr 19, 2023 pm 10:22 PM

Tool preparation Before we formally talk about the principle of synchronized, let's talk about spin locks first, because spin locks play a big role in the optimization of synchronized. To understand spin locks, we first need to understand what atomicity is. The so-called atomicity simply means that each operation is either not done or done. Doing all means that it cannot be interrupted during the operation. For example, to add one to the variable data, there are three steps: Load from memory into register. Add one to the value of data. Write the result back to memory. Atomicity means that when a thread is performing an increment operation, it cannot be interrupted by other threads. Only when this thread completes these three processes

Why does Java need to provide Lock instead of just using the synchronized keyword? Why does Java need to provide Lock instead of just using the synchronized keyword? Apr 20, 2023 pm 05:01 PM

Summary: The synchronized keyword is provided in Java to ensure that only one thread can access the synchronized code block. Since the synchronized keyword has been provided, why is the Lock interface also provided in the Java SDK package? Is this unnecessary reinvention of the wheel? Today, we will discuss this issue together. The synchronized keyword is provided in Java to ensure that only one thread can access the synchronized code block. Since the synchronized keyword has been provided, why is the Lock interface also provided in the Java SDK package? Is this unnecessary reinvention of the wheel? Today, let’s discuss it together

What is Java Synchronized What is Java Synchronized May 14, 2023 am 08:28 AM

What is Synchronized? Java readers are no strangers to the synchronized keyword. It can be seen in various middleware source codes or JDK source codes. For readers who are not familiar with synchronized, they only know that the synchronized keyword needs to be used in multi-threading. synchronized can ensure thread safety. It is called: mutex lock (only one thread can execute at the same time, other threads will wait), also called: pessimistic lock (only one thread can execute at the same time, other threads will wait). The JVM virtual machine will help you implement it. , developers only need to use the synchronized keyword. When using it, you need to use an object as a mutex for the lock

What is the difference between Lock and Synchronized in Java What is the difference between Lock and Synchronized in Java Apr 17, 2023 pm 07:19 PM

1. From a functional point of view, Lock and Synchronized are both tools used in Java to solve thread safety issues. 2. From a feature point of view, Synchronized is the synchronization keyword in Java, Lock is the interface provided in the J.U.C package, and this The interface has many implementation classes, including the implementation of reentrant locks such as ReentrantLock. Synchronized can control the strength of the lock in two ways. One is to modify the synchronized keyword at the method level, and the other is to modify it on the code block. You can use The life cycle of the synchronized lock object is used to control the scope of the lock. The lock object is a static object or a class pair.

See all articles