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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作