黑马程序员技术交流社区
标题:
多线程的安全问题
[打印本页]
作者:
HM何伟
时间:
2013-4-1 23:11
标题:
多线程的安全问题
本帖最后由 HM何伟 于 2013-4-2 00:25 编辑
这段代码有安全问题没??
class Single{
private Single(){}
private static Single s=null;
public static Single getOop()
{
synchronized(Single.class)
{
if (s==null)//?????????
try
{
Thread.sleep(20);
}
catch (Exception e)
{
}
s=new Single();
return s;
}
//return s;
}
}
class Test implements Runnable{
public void run()
{
while(true)
{
Single s = Single.getOop();
System.out.println(s);
}
}
}
class Main{
public static void main(String[] args){
Test t=new Test();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
t1.start();
t2.start();
t3.start();
}
}
复制代码
作者:
黑马李超
时间:
2013-4-1 23:46
if (s==null)//?????????
if的大括号呢,没有大括号,if不能判断,程序会不停new Single对象的
try
{
Thread.sleep(20);
}
catch (Exception e)
{
}
s=new Single();
return s;
作者:
陈丽莉
时间:
2013-4-2 00:01
记得及时处理帖子哦~
作者:
HM何伟
时间:
2013-4-2 00:24
黑马李超 发表于 2013-4-1 23:46
if (s==null)//?????????if的大括号呢,没有大括号,if不能判断,程序会不停new Single对象的
...
明白了,难怪地值会一直不一样
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2