62,614
社区成员
发帖
与我相关
我的任务
分享
/**
*
*/
package com.guo.singlepatterns;
/**
* 单例设计模式
* 懒汉式加载
* @author GYB
*
*/
public class Singleon02 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread01()).start();
}
}
//静态私有属性
private static Singleon02 instance;
//构造器私有化
private Singleon02(){
}
//提供方法访问instance
//加入了同步块,保证了线程的安全,降低了效率
public static synchronized Singleon02 getInstance() {
//return null==instance?(new Singleon02()):instance;
if (instance == null) {
instance = new Singleon02();
}
return instance;
}
}
class Thread01 implements Runnable{
public void run() {
System.out.println(Singleon02.getInstance());
}
}
/**
*
*/
package com.guo.singlepatterns;
/**
* 单例设计模式
* 懒汉式加载
* @author GYB
*
*/
public class Singleon02 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread01()).start();
}
}
//静态私有属性
private static Singleon02 instance;
//构造器私有化
private Singleon02(){
}
//提供方法访问instance
//加入了同步块,保证了线程的安全,降低了效率
public static synchronized Singleon02 getInstance() {
return null==instance?(new Singleon02()):instance;
// if (instance == null) {
// instance = new Singleon02();
// }
// return instance;
}
}
class Thread01 implements Runnable{
public void run() {
System.out.println(Singleon02.getInstance());
}
}
return null==instance?(new Singleon02()):instance;
return null==instance?(instance = new Singleon02()):instance;