使用关键字synchronized的写法比较多,常用的有如下几种
MyService代码
package chapter2.test2_2.test2_2_25;
public class MyService {
synchronized public static void testMethod1() {
}
public void testMethod2() {
synchronized (MyService.class) {
}
}
synchronized public void testMethod3() {
}
public void testMethod4() {
synchronized (this) {
}
}
public void testMethod5() {
synchronized ("abc") {
}
}
}
上面的代码中出现了3种类型的锁对象
- (A)testMethod1()和testMethod2()持有的锁是同一个,即MyService.java对应Class类的对象。
- (B)testMethod3()和testMethod4()持有的锁是同一个,即MyService.java类的对象。
- (C)testMethod5()持有的锁是字符串abc。
- 说明testMethod1()和testMethod2()是同步关系,
- testMethod3()和testMethod4()是同步关系。
- A和C之间是异步关系,
- B和C之间是异步关系,
- A和B之间是异步关系。