Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the content locked on the method by Java concurrent synchronized

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The main content of this article is to explain "what is the content that Java concurrent synchronized uses to lock on the method", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the content locked on the method by Java concurrent synchronized?"

What does synchronized use to lock on methods?

Locking the current method of the current object blocks other threads' access to the object's synchronized methods or blocks of code, but not non-synchronized methods.

Dirty reading

A common concept. In multithreading, it is inevitable that instance variables or global static variables of the same object will be accessed concurrently in multiple threads. If you do not do the correct synchronization processing, the result will be "dirty reading". That is, the data obtained has actually been changed. Note that there is no dirty reading of local variables here.

Public class ThreadDomain13 {private int num = 0; public void addNum (String userName) {try {if ("a" .equals (userName)) {num = 100; System.out.println ("a set over!"); Thread.sleep (2000);} else {num = 200; System.out.println ("b set over!") } System.out.println (userName + "num =" + num);} catch (InterruptedException e) {e.printStackTrace ();}

Write two threads to add the string "a" and the string "b" respectively:

Public class MyThread13_0 extends Thread {private ThreadDomain13 td; public MyThread13_0 (ThreadDomain13 td) {this.td = td;} public void run () {td.addNum ("a");}} public class MyThread13_1 extends Thread {private ThreadDomain13 td; public MyThread13_1 (ThreadDomain13 td) {this.td = td;} public void run () {td.addNum ("b");}}

Write a main function to run the two threads respectively:

Public static void main (String [] args) {ThreadDomain13 td = new ThreadDomain13 (); MyThread13_0 mt0 = new MyThread13_0 (td); MyThread13_1 mt1 = new MyThread13_1 (td); mt0.start (); mt1.start ();} / / take a look at the running result a set override set override num = 200a num = 200a

Normally, "a num = 100" and" b num = 200" should be printed, but now "b num = 200" and" a num = 200" are printed, which is a thread safety problem. We can think about how there is a thread safety problem:

1. Mt0 runs first, assigns a value of 100 to num, then prints out "a set over!" and goes to sleep

2. While mt0 is sleeping, mt1 runs, assigns a value of 200to num, then prints out "b set over!" and then prints "b num = 200"

3. Mt1 has finished sleeping. Since mt0's num and mt1's num are the same num, mt1 has changed num to 200.There is nothing mt0 can do about it. For it, num can only continue to run the code and print out "a num = 200".

The cause of the problem is analyzed, and the solution is very simple. You can add synchronization to the addNum (String userName) method:

Add the multithread synchronized keyword to the method

Public class ThreadDomain13 {private int num = 0; public synchronized void addNum (String userName) {try {if ("a" .equals (userName)) {num = 100; System.out.println ("a set over!"); Thread.sleep (2000);} else {num = 200; System.out.println ("b set over!") } System.out.println (userName + "num =" + num);} catch (InterruptedException e) {e.printStackTrace ();}

Take a look at the results of the run:

A set overwritten a num = 100b set overwritten num = 200b

Multiple objects, multiple locks.

In the case of synchronization, change the code in the main function:

Public static void main (String [] args) {ThreadDomain13 td0 = new ThreadDomain13 (); ThreadDomain13 td1 = new ThreadDomain13 (); MyThread13_0 mt0 = new MyThread13_0 (td0); MyThread13_1 mt1 = new MyThread13_1 (td1); mt0.start (); mt1.start ();}

Take a look at the results of the run:

A set overwritten set overwritten num = 200a num = 100A

Here is an important concept. Keyword synchronized acquired locks are object locks, rather than a section of code or method (function) as a lock, here if a code or method (function) as a lock, in fact, the acquisition is also an object lock, but the monitor (object) is different, which thread first executes the method with the synchronized keyword, which thread holds the lock of the object to which the method belongs, and other threads can only wait. But there is a premise: since a lock is called an object lock, it must be related to the object, so multiple threads must access the same object.

If multiple threads access multiple objects, the Java virtual machine creates multiple locks, as in the example above, two ThreadDomain13 objects are created, resulting in two locks. Since the two threads hold different locks, they are naturally not constrained by the behavior of "waiting for the lock to be released" and can run the code in addNum (String userName) separately.

What is locked by synchronized (this)?

The current object is locked. When the contents of the synchronized block are executed, the lock on the current object is released. If multiple threads access this object at the same time, it will be blocked.

What is locked by synchronized (object)?

It is the object object that is locked. When the contents of the synchronized block are executed, the lock on the object object is released. If multiple threads access this object at the same time, it will be blocked.

It is important to note that if object wraps classes for Integer, String, and so on (except for objects that come out of new), the current object is not locked and the thread is not blocked. Because the wrapper class is final and immutable, a new object is generated if you modify it. Therefore, after one thread modifies it, when other threads acquire the lock of the object, the object is no longer the original object, so it acquires the lock of another object, so there is no blocking.

At this point, I believe you have a deeper understanding of "what Java concurrent synchronized uses to lock up on the method". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report