thread 同步代码块

Java 为了解决 synchronized 方法某种情况下的弊端,提供了另一种同步的机制,即 同步代码块

但是这个实际是相对的,如果方法封装的足够小,只是封装了需要同步的代码片段,则使用 synchronized 修饰方法也是可以的

同步代码块只是不用 synchronized 修饰方法,而是修饰某一段代码,需要显式声明一个锁对象:

synchronized 修饰方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MyObject {

public synchronized void methodA() {
System.out.println("begin methodA threadName=" + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end methodA threadName=" + Thread.currentThread().getName());
}

}

synchronized 修饰代码块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MyObject {

private Object lock = new Object();

public void methodA() {
synchronized (lock) {
System.out.println("begin methodA threadName=" + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end methodA threadName=" + Thread.currentThread().getName());
}
}

}

不过两种机制独占的都是锁对象,synchronized 修饰方法锁具备的锁重入等特性对 synchronized 修饰代码块同样适用