Example sharing of synchronize function in Java
This article mainly introduces relevant information about the detailed explanation of the synchronize function in Java. I hope this article can help everyone understand how to use the synchronize function. Friends in need can refer to it
Detailed explanation of examples of synchronize function in Java
If a member function of a class in Java is modified with synchronized, it corresponds to the same object. Multiple threads must wait until they call the synchronization function of this object. The next thread can only call it after the previous thread has called it.
So if a class has two member functions that are modified by synchronized as shown in the code, for the same object, can one call funcA and the other call funcB when two threads are running?
Mysyn is such a class. If I have two threads, one runs funcA first and then funcB in the run method, and the other thread runs funcB first and then funcA in the run method. Is it possible that when outputting start A... then directly output start B...?
public class MySyn { public synchronized void funcA(String str){ System.out.println(str+":"); System.out.println("start A..."); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("...A end"); } public synchronized void funcB(String str){ System.out.println(str+":"); System.out.println("start B..."); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("...B end"); } }
The test code is as follows:
This thread runs funcA first
public class Mythread implements Runnable { private MySyn mysyn; private String id; public Mythread(MySyn syn, String id){ this.mysyn = syn; this.id = id; } @Override public void run() { this.mysyn.funcA(id); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.mysyn.funcB(id); } public static void main(String arg[]){ MySyn syn=new MySyn(); Thread t1 = new Thread(new Mythread(syn, "t1")); Thread t2 = new Thread(new YourThread(syn, "t2")); t1.start(); t2.start(); } }
This The thread runs funcB first
public class YourThread implements Runnable { private MySyn mysyn; private String id; public YourThread(MySyn syn, String id){ this.mysyn = syn; this.id=id; } @Override public void run() { this.mysyn.funcB(id); this.mysyn.funcA(id); } }
The output result is mostly:
t1: start A... ...A end t2: start B... ...B end t2: start A... ...A end t1: start B... ...B end
If you cancel the run method of Mythread Sleep between two function calls, the result is probably:
t1: start A... ...A end t1: start B... ...B end t2: start B... ...B end t2: start A... ...A end
Individual results may be different due to thread scheduling, but there will never be: start A...directly afterwards Output start B...
If funcB is not a synchronous function, what will be the result of the above code?
The code is slightly modified to remove the synchronized keyword of funcB. The running result is:
t2: t1: start A... start B... ...A end t1: start B... ...B end t2: start A... ...B end ...A end
Obviously the result of start A... is directly output after start B....
Similarly, if the Mysyn class has a public member variable, multi-threads can also modify the member variable by another thread while the synchronization function is being called.
The above experiment illustrates: Synchronized member functions can only have an exclusive effect on other synchronized functions (including itself) in the synchronized function call of the same object. That is, during multi-thread running, the same object is currently Only one synchronized function can be running, but this does not exclude other non-synchronized functions from running or accessing members.
Now suppose a class has two static synchronization methods, what about the situation?
I will not repeat the specific implementation, because the results are similar:
In multi-threading, the same class can currently only have one class synchronization function (static synchronization function) running. But it does not exclude the execution of other non-synchronized static functions or access to static members
The above is the detailed content of Example sharing of synchronize function in Java. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
