synchronized
Preface
I believe everyone has heard of thread safety issues. When learning operating systems, one knowledge point is critical resources. Simply put, only one A resource that allows one process to operate, but when we use multi-threading, we operate concurrently, and we cannot control the access and modification of only one resource at the same time. There are several operations that we want to control. Today we will talk about the second One method: thread synchronization block or thread synchronization method (synchronized)
Example
The following is an example
synchronized
Use of keywords
Thread synchronization method
public class Sychor {public void insert(Thread thread) {for (int i = 0; i < 10; i++) { System.out.println(thread.getName() + "输出: " + i); } }public static void main(String[] args) {final Sychor sychor = new Sychor(); Thread t1 = new Thread() {public void run() { sychor.insert(Thread.currentThread()); }; }; Thread t2 = new Thread() {public void run() { sychor.insert(Thread.currentThread()); }; }; t1.start(); t2.start(); } }
The output result is as shown below
It can be seen from the above results that the two threads here execute the
insert()
method at the same time. Below we will use the original code Add thesynchronized
keyword to see the effect. The code is as follows:
public class Sychor {public synchronized void insert(Thread thread) {for (int i = 0; i < 10; i++) { System.out.println(thread.getName() + "输出: " + i); } }public static void main(String[] args) {final Sychor sychor = new Sychor(); Thread t1 = new Thread() {public void run() { sychor.insert(Thread.currentThread()); }; }; Thread t2 = new Thread() {public void run() { sychor.insert(Thread.currentThread()); }; }; t1.start(); t2.start(); } }
I will not list the running results of the above program, you can do it yourself Try it. In short, you just add the
synchronized
keyword so that the threads are executed one by one. Only when one thread is executed first can another thread be executed.
Thread synchronization block
Of course we used the thread synchronization method above, we can use thread synchronization block, these two are more flexible than thread synchronization block, Just put the code that needs to be synchronized in the synchronization block. The code is as follows;
public class Sychor {public void insert(Thread thread) {synchronized (this) {for (int i = 0; i < 10; i++) { System.out.println(thread.getName() + "输出: " + i); } } }public static void main(String[] args) {final Sychor sychor = new Sychor(); Thread t1 = new Thread() {public void run() { sychor.insert(Thread.currentThread()); }; }; Thread t2 = new Thread() {public void run() { sychor.insert(Thread.currentThread()); }; }; t1.start(); t2.start(); } }
As can be seen from the above code, this method is more flexible. , you only need to put the code methods that need to be synchronized in the synchronization block, and the code that does not need to be synchronized outside
Detailed reasons
We know Each object has a lock. When we use the thread synchronization method or thread synchronization block, we actually obtain the only lock on the object. When a thread obtains this unique lock, then other The thread can only be shut out. Note that here we say it is an object, which means it is the same object. If it is a different object, it will not work because different objects have different object locks. For example, we Change the above program to the following:
public class Sychor {public void insert(Thread thread) {synchronized (this) {for (int i = 0; i < 10; i++) { System.out.println(thread.getName() + "输出: " + i); } } }public static void main(String[] args) {//第一个线程Thread t1 = new Thread() {public void run() { Sychor sychor = new Sychor(); //在run() 方法中创建一个对象sychor.insert(Thread.currentThread()); }; };//第二个线程Thread t2 = new Thread() {public void run() { Sychor sychor = new Sychor(); //创建另外的一个对象sychor.insert(Thread.currentThread()); }; }; t1.start(); t2.start(); } }
It can be seen from the above results that the thread synchronization block does not work at all at this time, because They call the insert method of different objects, and obtaining the lock is different
We have already said above that an object has a lock , the thread synchronization method and the thread synchronization block actually obtain the lock of the object, so the brackets of the thread synchronization block are filled with
this
, we all know thatthis
is in a class Meaning
A class also has a unique lock, what we said earlier is to use an object to call member methods , now if we want to call the static method in the class, then we can use the thread synchronization method or synchronization block to obtain the only lock in the class, then multiple threads can call the static method in the same class at the same time to achieve control Yes, the code is as follows:
public class Sychor {// 静态方法public static synchronized void insert(Thread thread) {for(int i=0;i<10;i++) { System.out.println(thread.getName()+"输出 "+i); } }public static void main(String[] args) {//第一个线程Thread t1 = new Thread() {public void run() { Sychor.insert(Thread.currentThread()); //直接使用类调用静态方法}; };//第二个线程Thread t2 = new Thread() {public void run() { Sychor.insert(Thread.currentThread()); //直接使用类调用静态方法}; }; t1.start(); t2.start(); } }
Note
To achieve thread safety and synchronization Control, if you are executing a non-
static
synchronized method or a synchronized block in it, you must use the same object. If you are calling a static synchronized method or a synchronized block in it, you must use the same class to call it.
If one thread accesses the
static
synchronization method, and another thread accesses the non-static synchronization method method, the two will not conflict at this time, because one is a class lock and the other is an object lock
If you use a thread synchronization block, the code in the synchronization block has controlled access, but the code outside is accessible to all threads
Reference article
- ##When an exception occurs in a thread that is executing a synchronized code block, then
jvm
will automatically release the lock occupied by the current thread, so there will be no deadlock due to exceptions
The above is the detailed content of What is synchronized? How to use synchronized?. For more information, please follow other related articles on the PHP Chinese website!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

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


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor