Home Java javaTutorial Example sharing of synchronize function in Java

Example sharing of synchronize function in Java

Sep 19, 2017 am 10:09 AM
java share

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"); 
  } 
}
Copy after login

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(); 
  } 
}
Copy after login

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); 
     
 
  } 
 
}
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

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

See all articles