A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李征雪 中级黑马   /  2012-4-15 15:24  /  1677 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Test
  2. {
  3.     private Test()
  4.     {
  5.         System.out.println("private");
  6.     }
  7.     static Test ts = null;
  8.     public static Test getTest()
  9.     {
  10.         return (null == ts ? ts = new Test() : null);
  11.     }
  12.     public void show()
  13.     {
  14.         System.out.println("hello private");
  15.     }
  16. }

  17. class DemoDanli
  18. {
  19.     public static void main(String[] args)
  20.     {
  21.         Test ts = Test.getTest();
  22.         ts.show();
  23.     }
  24. }
复制代码
请问第10行代码:return (null == ts ? ts = new Test() : null);这样写能否避免多线程访问产生的错误?是不是只要写一行代码就不会出错?

评分

参与人数 1技术分 +1 收起 理由
岳民喜 + 1

查看全部评分

3 个回复

倒序浏览
不能,多线程问题是两个线程操作一个对象,就像两个人要操作一个门一样,一个要开门,一个要关门,你说结果这个门会怎么样呢?!如果这个对象有一个读和写的方法,要是两个同时操作的话,肯定是不行的!想要多线程安全就麻烦点加锁解锁!还有你的那句话我有点不太理解啊,逻辑有点不顺,你要判断的是ts 而非 null   我觉得这样写比较好:ts==null ? ts=new Tist():null;   ts 只能产生一个对象,如果ts !=null  那么肯定就是Tist 的对象了,所以,我觉得你这句话我看着有点别扭啊!还不如if(ts==null){ts = new Tist()}

评分

参与人数 1技术分 +1 收起 理由
岳民喜 + 1

查看全部评分

回复 使用道具 举报


单例设计防止创建过多对象,但是依然需要同步

评分

参与人数 1技术分 +1 收起 理由
岳民喜 + 1

查看全部评分

回复 使用道具 举报
本帖最后由 陈扬 于 2012-4-15 16:19 编辑

你的代码不是单例模式
修改后后代码如下:
  1. class Test
  2. {
  3.     private Test()
  4.     {
  5.         System.out.println("private");
  6.     }
  7.     static Test ts = null;
  8.     public static Test getTest()
  9.     {
  10.             if(ts==null){ ts=new Test();}return ts;
  11.         //return (ts ==  null? ts = new Test() : null);/*返回结果*/
  12.     }
  13.     public void show()
  14.     {
  15.         System.out.println("hello private");
  16.     }
  17. }
  18. public class DemoDanli
  19. {
  20.     public static void main(String[] args)
  21.     {
  22.         Test ts = Test.getTest();
  23.         ts.show();
  24.         Test ts1 = Test.getTest();
  25.         //判断是不是同一个对象
  26.         System.out.println(ts==ts1);/*return (ts ==  null? ts = new Test() : null);返回结果为false*/
  27.                                                                 /*if(ts==null){ ts=new Test();}return ts;返回结果为true*/
  28.     }
  29. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
岳民喜 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马