多线程下的懒汉模式,同步代码块和同步方法

来源:互联网 发布:中班美工交通标志教案 编辑:程序博客网 时间:2024/05/29 15:07
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;}}

0 0