1、synchronized关键字修饰的同步函数使用什么对象作为锁?
进入f1
离开f1
进入f2
我们可以看到,只有当线程t1释放锁后,线程t2才能进入f2,说明同步方法和同步代码块采用的是同一个this锁,class锁的测试则给f1添加static关键字,f2使用test.class锁。
分为两种情况,如果该函数为静态的则采用所在类的class锁,否则采用this锁,测试用例如下:
class test{
public synchronized void f1() throws InterruptedException{
System.out.println("进入f1");
Thread.sleep(5000);
System.out.println("离开f1");
}
public void f2(){
synchronized (this){
System.out.println("进入f2");
}
}
}
public class thread{
public static void main(String[] args) throws InterruptedException {
test t=new test();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
t.f1();
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
t.f2();
}
});
t1.start();
t2.start();
}
}
输出结果:
进入f1
离开f1
进入f2
我们可以看到,只有当线程t1释放锁后,线程t2才能进入f2,说明同步方法和同步代码块采用的是同一个this锁,class锁的测试则给f1添加static关键字,f2使用test.class锁。