1、this monitor
synchronized关键字直接写在非静态方法上的method1效果和作用在this monitor的method2效果等同。
注意:由于作用的是this monitor,所以该对象在调用method1的时候,this monitor加锁会导致该对象其他争抢该锁的方法进入阻塞(即method1执行过程中会导致method2阻塞,反之亦然)
package com.practice.concurrent.chapter04.sync;
import java.util.concurrent.TimeUnit;
public class ThisMonitor {
public synchronized void method1(){
System.out.println(Thread.currentThread().getName()+"enter to method1");
try {
TimeUnit.MINUTES.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void method2(){
synchronized(this){
System.out.println(Thread.currentThread().getName()+"enter to method2");
try {
TimeUnit.MINUTES.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThisMonitor thisMonitor = new ThisMonitor();
new Thread(thisMonitor::method1).start();
new Thread(thisMonitor::method2).start();
}
}
2、Class monitor
synchronized关键字直接写在静态方法上的method1效果和作用在ClassMonitor.class的method2效果等同。
注意:如果使用ClassMonitor会导致该类型的所有争抢该锁的方法同时只有一个能够执行(包括同一个类型下的所有对象调用该类方法也会阻塞,同时只有一个运行)
package com.practice.concurrent.chapter04.sync;
import java.util.concurrent.TimeUnit;
public class ClassMonitor {
public static synchronized void method1(){
System.out.println(Thread.currentThread().getName()+" enter to method1");
try {
TimeUnit.MINUTES.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void method2(){
synchronized(ClassMonitor.class){
System.out.println(Thread.currentThread().getName()+" enter to method2");
try {
TimeUnit.MINUTES.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Thread(ClassMonitor::method1).start();
// new Thread(ClassMonitor::method2).start();
ClassMonitor classMonitor = new ClassMonitor();
new Thread(){
@Override
public void run() {
classMonitor.method2();
}
}.start();
}
}
详见 :https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html