Home  >  Article  >  Java  >  What special monitor is there in java?

What special monitor is there in java?

WBOY
WBOYforward
2023-05-17 08:58:441254browse

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();
    }
}
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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete