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();
}
}
}
上記は私が試したコードです。同期された1つのクラス(Test2.class)にすべてのコードを記述したところ、奇妙なことが起こりました。foo()メソッドを呼び出した後、すぐにbar()メソッドを呼び出すことができません。同じオブジェクトをロックしていると思います。この奇妙なことを説明する方法。