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.

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo


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

SublimeText3 Chinese version
Chinese version, very easy to use

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.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
