您的位置:首页 > 其它

懒汉式的安全优化方式,两种方式。线程同时运行的时候,不会创建两个对象

2017-08-18 16:42 253 查看
/**
* 懒汉式的安全优化方式,两种方式。
*
* @author jiaxutianhuo
*
*/
public class Singleton {

// 私有化构造
private Singleton() {
// 私有化构造函数,不能用new Singleton来创造对象。
// 只能通过getInstance创造对象,也就是用同一个对象。
System.out.println("对象创建成功。");
}

// 全局对象
private static Singleton singleton = null;

// 懒汉式是非线程安全的。解决方式如下:
// 关键字:synchronized:可用来给对象和方法或者代码块加锁,
// 当它锁定一个方法或者一个代码块的时候,同一时刻最多只要一个线程执行这个代码。
public static synchronized Singleton getInstance() {
// 判断全局对象是否为空。
if (singleton == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 休眠一秒钟,检测多线程的运行情况。
// 如果为空,就创建该类对象。
singleton = new Singleton();
}
// 如果不为空,就直接返回该对象。
// 因为第一次创建的时候,就不为空了,
// 所以在此创建的时候,判断不为空,直接返回该对象,
// 所以两个对象是代表的一个对象。就是第一次创建的对象。
return singleton;
}
///**
// * 使用双重检测机制,实现线程安全的懒汉式
// * @return
// */
//	public static  Singleton getInstance() {
//		// 判断全局对象是否为空。
//		if (singleton == null) {
//			synchronized(Singleton.class){
//				if (singleton == null) {
//					singleton = new Singleton();
//				}
//			}
//
//		}
//		return singleton;
//	}
public static void main(String[] args) {
//多线程操作
//创建多线程方式2:直接使用Thread操作
/**
* 如果没有synchronized,就会被两个线程同时创建,创建两个对象。
*/
Thread thread1=new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
//
Singleton ton=Singleton.getInstance();
System.out.println(ton.hashCode());
}
};
thread1.start();
Thread thread2=new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
Singleton ton2=Singleton.getInstance();
System.out.println(ton2.hashCode());
}
};
//开启新线程
thread2.start();
//此方法创建对象,ton1和ton2是同一个对象。
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐