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