单例模式
import java.io.*; class singleton { Integer y = 2; private static volatile singleton instance = null; public static singleton getInstance() { if (instance == null) { synchronized(singleton.class) { if (instance == null) { instance = new singleton(); } } } return instance; } public singleton(){} } class test { public static void main (String[] args) throws java.lang.Exception { singleton x = singleton.getInstance(); System.out.print(x.y); } }
suqiandeMacBook-Pro:~/Tmp$ javac test.java
suqiandeMacBook-Pro:~/Tmp$ java test
2
suqiandeMacBook-Pro:~/Tmp$