public class Foo {
private static Foo foo;
private Foo(){}
public static Foo getInstance(){
if (foo==null){
try {
Thread.sleep(1);
} catch (InterruptedException e) {}
foo = new Foo();
System.out.println(foo+"----"+Thread.currentThread().getName());
}
return foo;
}
public static void main(String[] args) throws Exception {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
Foo foo1 = Foo.getInstance();
}
},"thread1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
Foo foo2 = Foo.getInstance();
}
},"thread2");
thread1.start();
thread2.start();
}
}
これらのコードはマルチスレッド環境では安全ではないことをシミュレートしたいだけですが、常に次のような2つの同じオブジェクトを出力します:
Foo@24c21495----thread1
Foo@24c21495----thread2
また
Foo@3d4b7453----thread1
Foo@3d4b7453----thread2
...
なぜ?