今天忽然很好奇 java 中的 Synchronized 到底锁的什么?锁一般可以理解为互斥的资源,在java 中万物皆对象。那么Synchronized 肯定是锁住了一个对象,或者有一个对象作为了互斥资源。那么Synchronized 到底锁了什么对象。
Synchronized 共有两种使用方式
1、修饰方法
tips:我将静态方法和非静态方法统称为方法
public synchronized void test(){}
2、代码块
synchronized (object){
}
其实代码块的方式,已经表明了锁的是什么对象
synchronized (object){
// 锁的object对象
}
synchronized (SyncTest.class){
// 锁的SyncTest class 对象
}
那么修饰方法时锁的是什么?我们通过测试用例测试下
非静态方法
public class SyncTest {
public synchronized void test1(){
System.out.println("test1 in");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test1 out");
}
public synchronized void test2(String name){
System.out.println(name+" test2 in");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " test2 out");
}
}
public static void main(String[] args) throws InterruptedException {
SyncTest syncTest = new SyncTest();
SyncTest syncTest2 = new SyncTest();
Thread a= new Thread(()->syncTest.test1());
Thread b= new Thread(()->syncTest.test2("b"));
Thread c= new Thread(()->syncTest2.test2("c"));
a.start();
b.start();
c.start();
TimeUnit.SECONDS.sleep(20);
System.out.println("end");
}
输出
test1 in
c test2 in
test1 out
b test2 in
c test2 out
end
b test2 out
可以看出线程a和b 顺序执行,c线程不收a、b影响。这就表明synchronized 修饰非静态方法时,锁住的是当前对象
那么修饰静态方法呢
测试code
public class SyncTest {
public static synchronized void test1(){
System.out.println("test1 in");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test1 out");
}
public synchronized void test2(){
System.out.println("test2 in");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test2 out");
}
}
public static void main(String[] args) throws InterruptedException {
SyncTest syncTest = new SyncTest();
Thread a= new Thread(()->syncTest.test1());
Thread b= new Thread(()->syncTest.test2());
a.start();
b.start();
TimeUnit.SECONDS.sleep(20);
System.out.println("end");
}
输出
test1 in
test2 in
test1 out
test2 out
end
这个表明synchronized 修饰静态方法时锁住的是当前class 对象。
网友评论