使用static代码块实现单例模式

编程

public class MyObject {

private static MyObject instance = null;

public MyObject() {

}

static {

instance = new MyObject();

}

public static MyObject getInstance(){

return instance;

}

}

public class MyThread extends Thread{

@Override

public void run() {

System.out.println(MyObject.getInstance().hashCode());

}

}

public class Run {

public static void main(String[] args) {

MyThread myThread = new MyThread();

MyThread myThread1 = new MyThread();

MyThread myThread2 = new MyThread();

myThread.start();

myThread1.start();

myThread2.start();

}

}

下一节:使用enum枚举实现单例模式

以上是 使用static代码块实现单例模式 的全部内容, 来源链接: utcz.com/z/513445.html

回到顶部