黑马程序员技术交流社区
标题:
帮忙分析以下代码,在多线程中,来运用懒汉式
[打印本页]
作者:
黑马黄文龙
时间:
2012-12-8 20:12
标题:
帮忙分析以下代码,在多线程中,来运用懒汉式
本帖最后由 黑马黄文龙 于 2012-12-8 23:19 编辑
帮忙分析以下代码,在多线程中,来运用懒汉式,然后看两个线程创建的对象是否为同一个对象,后面突然没思路了.......
/*
需求:把单例模型运用到多线程中
分析:
1,创建一个单例模型
2,定义一个Test类,测试两个线程获得对象是不是同一个对象
*/
//创建一个单例类
class SingleOne_Thread
{
private static SingleOne_Thread one;
private SingleOne_Thread(){}
//对外有一个公共访问方法来获得单例类的对象
public static SingleOne_Thread getOne()
{
if(one==null)
{
one=new SingleOne_Thread();
return one;
}
}
}
//有实现Runnable接口的方式来创建线程,并且重写run方法
class Thread_Test implements Runnable
{
public void run()
{
SingleOne_Thread.getOne();
System.out.println(Thread.currentThread().getName());
}
}
//定义一个Test类,来测试两个线程获得对象是不是同一个对象
public class Test
{
public static void main(String[]args)
{
Runnable rt=new Thread_Test();
Thread t1=new Thread(rt);
Thread t2=new Thread(rt);
t1.start();
t2.start();
}
}
复制代码
作者:
赵保磊
时间:
2012-12-8 22:07
/*
把单例模式应用到多线程中
*/
class singleElement
{
private singleElement(){}
private static singleElement se=null;
public static singleElement getSe()
{
se=new singleElement();
return se;
}
}
class sorr implements Runnable
{
public void run()
{
synchronized(sorr.class)
{
singleElement newSe=singleElement.getSe();
System.out.println(Thread.currentThread().getName()+":::"+newSe);
}
}
}
class aaaDemo
{
public static void main(String[] args)
{
sorr s=new sorr();
Thread t1=new Thread(s);
Thread t2=new Thread(s);
t1.start();
t2.start();
}
}
作者:
xjandrew
时间:
2012-12-8 22:08
本帖最后由 xjandrew 于 2012-12-8 22:11 编辑
class SingleOne_Thread
{
private static SingleOne_Thread one;
private SingleOne_Thread(){}
//对外有一个公共访问方法来获得单例类的对象
public static SingleOne_Thread getOne()
{
if(one==null)
{
one=new SingleOne_Thread();
return one;
}
else//这里出的问题,你仅有if情况下的返回值,当one!=null时怎办?(其实else可以不写)
return null;//这里必须得返回个类型值,null是我随便加的,你依自己的需求来
}
}
复制代码
作者:
xjandrew
时间:
2012-12-8 22:15
按2楼的例子来说,这样就行
class SingleOne_Thread
{
private static SingleOne_Thread one;
private SingleOne_Thread(){}
//对外有一个公共访问方法来获得单例类的对象
public static SingleOne_Thread getOne()
{
return new SingleOne_Thread();
}
}
复制代码
作者:
黑马黄文龙
时间:
2012-12-8 23:17
xjandrew 发表于 2012-12-8 22:08
谢谢!!!
作者:
黑马黄文龙
时间:
2012-12-8 23:17
赵保磊 发表于 2012-12-8 22:07
/*
把单例模式应用到多线程中
*/
谢谢!回答的很详细!!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2