- class Single {
- private Single() {
- };
- static Object obj = new Object();
- private static Single s = null;
- /**
- * 用同步代码块,不需要每次都判断锁,效率高
- */
- public static Single getSingle1() {
- if (s == null) {
- synchronized (obj) {
- if (s == null) {
- s = new Single();
- }
- }
- }
- return s;
- }
- /**
- * 用同步方法,每次都需要判断锁,效率低
- */
- public static synchronized Single getSingle2() {
- if (s == null) {
- s = new Single();
- }
- return s;
- }
- }
复制代码
|
|