在单例模式的懒汉模式中,为了解决多线程的问题,使用了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;
}
}
单例对象是static的,不会释放
synchronized保证了其中的代码,只能同时被一个线程执行,如果别的线程要执行,会等待前者执行完再执行。
几个线程同调用getInstance() 创建对象,因为有同步锁,所以只有一个线程能获取到,其他线程处于等待状态,当这个线程调用方法结束后释放锁,等待中的线程会再去竞争锁。
但是并不建议你使用这种方式创建单例对象,相关知识可以关注我的博客,看看《设计模式-单例模式》和《java并发编程基础》这两篇博文。