黑马程序员技术交流社区

标题: 多线程的安全问题 [打印本页]

作者: HM何伟    时间: 2013-4-1 23:11
标题: 多线程的安全问题
本帖最后由 HM何伟 于 2013-4-2 00:25 编辑

这段代码有安全问题没??
  1. class Single{
  2.          private Single(){}
  3.          private static Single s=null;
  4.          public static Single getOop()
  5.          {
  6.                 synchronized(Single.class)
  7.                 {                                
  8.                         if (s==null)//?????????
  9.                
  10.                         try
  11.                                 {
  12.                                   Thread.sleep(20);
  13.                                 }
  14.                                 catch (Exception e)
  15.                                 {
  16.                                 }
  17.                                 
  18.                                 s=new Single();
  19.                           return s;
  20.                 }
  21.                  //return s;
  22.          }
  23. }
  24. class Test implements Runnable{
  25.         public void run()
  26.         {
  27.           while(true)
  28.          {
  29.                 Single s = Single.getOop();
  30.                    System.out.println(s);
  31.          }
  32.         }
  33. }
  34. class Main{

  35.         public static void main(String[] args){
  36.                            Test t=new Test();
  37.                         Thread t1=new Thread(t);
  38.                         Thread t2=new Thread(t);
  39.                         Thread t3=new Thread(t);
  40.                         t1.start();
  41.                         t2.start();
  42.                         t3.start();
  43.                  
  44.         }
  45. }
复制代码

作者: 黑马李超    时间: 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