Home > Java > javaTutorial > body text

What special monitor is there in java?

WBOY
Release: 2023-05-17 08:58:44
forward
1425 people have browsed it

Explanation

1. this monitor: synchronized on a member method is this monitor, which is equivalent to using synchronized(this) in a method

2 , class monitor: synchronized on a static method is a class monitor, which is equivalent to using synchronized(XXX.class)

Instance

public class Main {
    public synchronized void method1(){
        System.out.println(Thread.currentThread().getName()+" method1");
        try{
            TimeUnit.MINUTES.sleep(5);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
 
    public synchronized void method2(){
        System.out.println(Thread.currentThread().getName()+" method2");
        try{
            TimeUnit.MINUTES.sleep(5);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        Main m = new Main();
        new Thread(m::method1).start();
        new Thread(m::method2).start();
    }
}
Copy after login
in a static method

The above is the detailed content of What special monitor is there in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template