您的位置:首页 > 编程语言 > Java开发

java多线程问题总结

2016-08-29 19:30 232 查看
1、synchronized关键字修饰的同步函数使用什么对象作为锁?

分为两种情况,如果该函数为静态的则采用所在类的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锁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  synchronized this