synchronized是java关键字层面上的锁,可是他锁的对象是什么呢?我们一起来看下。
示例:
public class A {
public static void main(String[] args) {
Demo demo1 = new Demo();
new Thread(() -> {demo1.test1();}, "A").start();
new Thread(() -> {demo1.test2();}, "B").start();
}
static class Demo {
public synchronized void test1() {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("coding11111");
}
public synchronized void test2() {
System.out.println("coding22222");
}
}
}
控制台打印:
coding11111
coding22222
毫无疑问是按顺序去竞争锁资源,coding1先拿到锁执行完释放锁再执行coding2。
那如果是不同线程访问不同的对象呢
public class A {
public static void main(String[] args) {
Demo demo1 = new Demo();
Demo demo2 = new Demo();
new Thread(() -> {demo1.test1();}, "A").start();
new Thread(() -> {demo2.test2();}, "B").start();
}
static class Demo {
public synchronized void test1() {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("coding11111");
}
public synchronized void test2() {
System.out.println("coding22222");
}
}
}
控制台打印:
coding22222
coding11111
这时候我们发现线程2没有等待线程1执行完释放锁再去执行自己的代码,那就证明他俩竞争的不是同一把锁。
结论:普通方法中 synchronized锁的对象是方法的调用者
那么问题来了,静态方法会不会不一样呢?
修改demo
public class A {
public static void main(String[] args) {
Demo demo1 = new Demo();
new Thread(() -> {Demo.test1();}, "A").start();
new Thread(() -> {demo1.test2();}, "B").start();
}
static class Demo {
// 锁静态方法
public static synchronized void test1() {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("coding11111");
}
// 锁普通方法
public synchronized void test2() {
System.out.println("coding22222");
}
}
}
控制台打印:
coding22222
coding11111
发现线程2仍然没有等待线程1,那就证明他俩用的还不是同一把锁,怎么回事呢? 这时候我们就要思考一下,静态方法是在初始化是时候就被调用了,那么意味着这把锁在类被加载的时候就存在了,锁的是Class类,而普通方法锁的是对象的调用者。两者不一样。因此线程2没有等待线程1执行完再执行。
那如果是两个static类被synchronized修饰呢?
public class A {
public static void main(String[] args) {
new Thread(() -> {Demo.test1();}, "A").start();
new Thread(() -> {Demo.test2();}, "B").start();
}
static class Demo {
public static synchronized void test1() {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("coding11111");
}
public static synchronized void test2() {
System.out.println("coding22222");
}
}
}
控制台打印:
coding11111
coding22222
可以看到线程顺序执行,那就证明是同一把锁,前面说过静态方法锁的是Class类,而类信息全局唯一,因此锁的目标只能是同一个东东。
总结:
synchronized锁普通方法时,锁的目标是方法的调用者
synchronized锁静态方法时,锁的目标是Class类信息。(类信息全局唯一)
无聊的知识又增加了~