aaqian1 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保证了其中的代码,只能同时被一个线程执行,如果别的线程要执行,会等待前者执行完再执行。

    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退