在单例模式的懒汉模式中,为了解决多线程的问题,使用了synchronized,那这个是不是意味着只有一个线程可以获得这个实例,那要是这个线程释放这个实例对象了,其他线程怎么知道呢?或者说Singleton类怎么知道呢?
public class Test2 {
public static void main(String[] args) throws InterruptedException {
for(int i =0;i<3;i++) {
MyThread thread = new MyThread();
thread.start();
System.out.println("== 创建线程 ==");
Thread.sleep(2000);
}
}
}
class MyThread extends Thread{
public void run() {
Singleton singleton = Singleton.getInstance();
try {
singleton = null; //将创建的对象置为null
System.out.println("销毁实例对象");
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(instance == null) { //难道是只能执行一次??
instance = new Singleton();
System.out.println("创建singleton对象!");
}
return instance;
}
}