0%

java | 多把锁

synchronized 会把整个对象加锁。比如 如果是 synchronized(this) 会把这个实例加锁。

部分方法虽然互斥,但是,依然会进行无效等待。

synchronized(this)

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
44
45
46
package com.redisc;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.Run")
public class Run {


public static void main(String[] args) throws Exception {
BigRoom bigRoom = new BigRoom();
new Thread(() -> {
try {
bigRoom.study();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

new Thread(() -> {
try {
bigRoom.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}

}

@Slf4j(topic = "c.BigRoom")
class BigRoom {

public void sleep() throws InterruptedException {
synchronized (this) {
log.debug("sleep...");
Thread.sleep(2000);
}
}

public void study() throws InterruptedException {
synchronized (this) {
log.debug("study...");
Thread.sleep(1000);
}
}
}

synchronized(Object)

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
44
45
46
47
48
package com.redisc;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.Run")
public class Run {


public static void main(String[] args) throws Exception {
BigRoom bigRoom = new BigRoom();
new Thread(() -> {
try {
bigRoom.study();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

new Thread(() -> {
try {
bigRoom.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}

}

@Slf4j(topic = "c.BigRoom")
class BigRoom {
private final Object studyRoom = new Object();
private final Object bedRoom = new Object();

public void sleep() throws InterruptedException {
synchronized (studyRoom) {
log.debug("sleep...");
Thread.sleep(2000);
}
}

public void study() throws InterruptedException {
synchronized (bedRoom) {
log.debug("study...");
Thread.sleep(1000);
}
}
}
请我喝杯咖啡吧~