嘿,这个问题蛮奇怪!
wtjd 2005-11-30 07:48:53 大家看看下面的代码:
public class TestThread extends Thread{
public String msg = "Hi!";
public synchronized void f1(){
System.out.println("f1!");
}
public synchronized void f2(){
System.out.println("f2!");
}
public synchronized void run(){
this.f1();
this.f2();
}
public static void main(String[] args){
TestThread test1 = new TestThread();
TestThread test2 = new TestThread();
test1.start();
test2.start();
}
}
你猜猜会输出什么?
你肯定会说: 输出f1和f2
告诉你答案是正确的,可是。。。。
我们知道Java的线程在执行时会在有synchronized的函数块所在类加上一把锁,对吧?并且每个对象只有一把锁,只有取得了该对象的锁,才能继续执行它的同步方法,对吧?
在上述代码中 run方法我加上了synchronized,也就是说run方法在执行时,run方法所在的类TestThread就会加上一把锁,此时我在run中调用f1方法,f1方法同样也被synchronized同步了起来,f1方法所在的类也是TestThread,如果我想调用f1的话,我也得取得f1所在类TestThread的锁呀,可是刚才锁不是被run所在的线程占有了吗?同样,f2也一样,
为什么上面还会输出f1和f2呢?不解,真是奇怪!