小迷糊171 2019-10-29 20:33 采纳率: 0%
浏览 345

单例模式的懒汉模式的多线程问题

在单例模式的懒汉模式中,为了解决多线程的问题,使用了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;
    }
}
  • 写回答

2条回答 默认 最新

  • threenewbee 2019-10-29 23:23
    关注

    单例对象是static的,不会释放
    synchronized保证了其中的代码,只能同时被一个线程执行,如果别的线程要执行,会等待前者执行完再执行。

    评论

报告相同问题?