我们知道synchronized关键词加在方法上可以对方法加上锁,让不同线程执行该方法抢占锁来顺序执行,我们知道对静态方法锁定的时候是对该类class对象上加上锁,而非静态方法上锁时会对该实例对象头上锁,那假设我用两个不同线程对静态方法和非静态方法分别调用执行,它们会互斥执行吗?
/**
* 静态和非静态synchronized锁定方法测试
* @author humorchen
* @date 2023/1/10 16:47
*/
public class StaticAndNotStaticTest {
public static synchronized void staticSay() {
System.out.println("static say begin");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("static say end");
}
public synchronized void notStaticSay() {
System.out.println("not static say begin");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("not static say end");
}
public static void main(String[] args) {
StaticAndNotStaticTest staticAndNotStaticTest = new StaticAndNotStaticTest();
Thread notStaticThread = new Thread(() -> {
staticAndNotStaticTest.notStaticSay();
});
Thread staticThread = new Thread(() -> {
StaticAndNotStaticTest.staticSay();
});
notStaticThread.start();
staticThread.start();
try {
notStaticThread.join();
staticThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
五秒后
得出结论,不互斥,原因是它们锁的对象不一样,一个是类,一个是实例对象