synchronized 和 static synchronized

挺简单的一个问题,今天被人问起了顺手写一下。

其实 synchronized 是实例对象锁,而 static 是类对象锁。每个类类对象在一个classloader只会有一个。

下面两段简单的代码就能验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package lock;

import com.meta.mq.common.utils.ThreadUtil;

/**
* @author : haifeng.pang.
* @version 0.1 : Human v0.1 2021/1/28 下午5:48 By haifeng.pang.
* @description :
*/
public class Human {

public synchronized void say(String name) {
System.out.println("say " + name);
ThreadUtil.quietSleep(10000);
}

public synchronized void eat(String name) {
System.out.println("eat " + name);
}

public static synchronized void sayStatic(String name) {
System.out.println("static say" + name);
}

public static synchronized void eatStatic(String name) {
System.out.println("static eat" + name);
ThreadUtil.quietSleep(10000);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package lock;

/**
* @author : haifeng.pang.
* @version 0.1 : Test v0.1 2021/1/28 下午5:49 By haifeng.pang.
* @description :
*/
public class Test {


@org.junit.Test
public void test() {
Human human = new Human();
Human human1 = new Human();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
human.say("im threadA");
}
});

Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
human.eat("im threadB");

}
});

threadA.start();

threadB.start();

try {
threadA.join();
threadB.join();
}catch (Exception e) {
//
}


}
}