你能告诉我以下的调用是否可以重入?
public class Foo {
public synchronized void doSomething() {}
public synchronized void doAnotherSomething() {}
}
public class Too {
private Foo foo;
public synchronized void doToo() {
foo.doSomething();
//...other thread interfere here....
foo.doAnotherSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
方法doToo()
可重入的2个连续调用?我不确定这种情况,因为foo.doSomething()
方法获取并释放内部锁,两次调用之间没有嵌套同步.是否存在其他线程可能在两次调用之间发生干扰的情况?
为什么下面的代码不会导致死锁?我的意思是在我调用getNumber(.)后,类Test的对象应该被锁定,所以我不能访问getNumber2(.).
class Test() {
synchronized int getNumber(int i){
return getNumber2(i);
}
synchronized int getNumber2(int i) {
return i;
}
public static void main(String[] args) {
System.out.println((new Test()).getNumber(100));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
100
Run Code Online (Sandbox Code Playgroud)