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();
}
}
我只想模拟这些代码在多线程环境中是不安全的,但它总是输出两个相同的对象,例如:
Foo@24c21495----thread1
Foo@24c21495----thread2
或者
Foo@3d4b7453----thread1
Foo@3d4b7453----thread2
...
为什么?