`

单例模式

阅读更多
单例类
public class Singleton {

private Singleton() {
  System.out.println("Singleton init");
  this.slowdown();
}

private static class SingtonHolder {
  private static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
  return SingtonHolder.instance;
}

private void slowdown() {
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
}
}

测试类
public class SingletonTest extends Thread {
public void run() {
  Singleton s = Singleton.getInstance();
  System.out.println(this.getName() + ": s = " + s);
}

public SingletonTest(String name) {
  super(name);
}

public static void main(String[] args) {
  new SingletonTest("A").start();
  new SingletonTest("B").start();
  new SingletonTest("C").start(); }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics