public class Test2 {
static int count;
public static void main(String[] args) {
final Test2 t1 = new Test2();
final Test2 t2 = new Test2();
new Thread(new Runnable() {
@Override
public void run() {
t1.foo();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t1.bar();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t2.foo();
}
}).start();
}
public static synchronized void foo() {
synchronized (Test2.class) {
System.out.println("run bar"+count++);
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static synchronized void bar() {
System.out.println("run bar");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上是我尝试过的代码。当我在一个同步的类(Test2.class)中编写所有代码时,我发现发生了一些奇怪的事情。调用 foo() 方法后,我无法立即调用 bar() 方法。我认为它锁定了同一个对象。如何解释这个奇怪的事情。