In Java, the synchronized keyword is used to control thread synchronization, which is to control the synchronized code segment from being executed by multiple threads at the same time in a multi-threaded environment. synchronized can be added to a piece of code or a method.
The key is, don’t think that everything will be fine if you add synchronized to a method or code segment. Look at the following piece of code:
public synchronized void test() { System.out.println("test开始.."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test结束.."); } } class MyThread extends Thread { public void run() { Sync sync = new Sync(); sync.test(); } } public class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { Thread thread = new MyThread(); thread.start(); } } }
Run results: test starts.. test starts.. test starts.. test ends.. test ends.. test End..
It can be seen that the above program starts three threads and runs the test() method in the Sync class at the same time. Although the test() method is synchronized, it still runs at the same time. It seems that synchronized does not work. .
Remove synchronized from the test() method, and add synchronized(this) inside the method:
public void test() { synchronized(this){ System.out.println("test开始.."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test结束.."); } }
Running results: test starts.. test starts.. test starts.. test ends.. test ends.. test ends ..
Everything is still so calm, I don’t see synchronized working.
In fact, synchronized(this) and non-static synchronized methods (as for the static synchronized method, please read below), can only prevent multiple threads from executing the synchronization code segment of the same object at the same time.
Back to the title of this article: does synchronized lock code or objects. The answer is: synchronized locks the object in the brackets, not the code. For non-static synchronized methods, what is locked is the object itself, which is this.
When synchronized locks an object, if other threads also want to get the lock of this object, they must wait for the thread to finish executing and release the lock before locking the object again, so as to achieve the purpose of thread synchronization. Even if two different code segments have to lock the same object, the two code segments cannot run at the same time in a multi-threaded environment.
So when we use the synchronized keyword, we should narrow the scope of the code segment as much as possible. If we can add synchronization to the code segment, we should not add synchronization to the entire method. This is called reducing the granularity of the lock and making the code more concurrent. The reason is based on the above thinking, the lock code segment is too long, other threads will have to wait for a long time, and the flowers of waiting will fade. Of course, this paragraph is a digression and has little to do with the core idea of this article.
Looking at the above code, each thread has a new Sync class object, which means three Sync objects are generated. Since they are not the same object, multiple threads can run synchronized methods or code segments at the same time.
In order to verify the above point of view, modify the code so that three threads use the same Sync object.
class MyThread extends Thread { private Sync sync; public MyThread(Sync sync) { this.sync = sync; } public void run() { sync.test(); } } public class Main { public static void main(String[] args) { Sync sync = new Sync(); for (int i = 0; i < 3; i++) { Thread thread = new MyThread(sync); thread.start(); } } }
Running result: test starts.. test ends.. test starts.. test ends.. test ends.. test starts.. test ends..
You can see that synchronized has taken effect at this time.
So, if you really want to lock this code, what should you do? That is, if it is still the original piece of code and each thread creates a new Sync object, how can we prevent the test method from being executed by multiple threads.
The solution is also very simple, just lock the same object. For example, locking the same fixed object in the parentheses after synchronized is fine. This is no problem, but the more common approach is to let synchronized lock the Class object corresponding to this class.
class Sync { public void test() { synchronized (Sync.class) { System.out.println("test开始.."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test结束.."); } } } class MyThread extends Thread { public void run() { Sync sync = new Sync(); sync.test(); } } public class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { Thread thread = new MyThread(); thread.start(); } } }
Running result: test starts.. test ends.. test starts.. test ends.. test starts.. test ends..
The above code uses synchronized (Sync.class) to achieve the effect of global lock.
static synchronized method. The static method can be called directly by adding the class name and method name. This cannot be used in the method, so it locks not this, but the Class object of the class. Therefore, the static synchronized method is also equivalent to a global lock, which is equivalent to Code segment is locked.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment