请问为什么使用三元运算符和if 这里会有不同的结果。。。

Gump1112 2017-12-01 03:53:10
先看if判断的。
/**
*
*/
package com.guo.singlepatterns;

/**
* 单例设计模式
* 懒汉式加载
* @author GYB
*
*/
public class Singleon02 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread01()).start();
}
}
//静态私有属性
private static Singleon02 instance;
//构造器私有化
private Singleon02(){

}
//提供方法访问instance
//加入了同步块,保证了线程的安全,降低了效率
public static synchronized Singleon02 getInstance() {
//return null==instance?(new Singleon02()):instance;
if (instance == null) {
instance = new Singleon02();
}
return instance;
}

}
class Thread01 implements Runnable{
public void run() {
System.out.println(Singleon02.getInstance());
}
}


此时输出的 地址相同表示 instance没有发生变化
当改为三元运算符时 结果时 地址都不同 如下
/**
*
*/
package com.guo.singlepatterns;

/**
* 单例设计模式
* 懒汉式加载
* @author GYB
*
*/
public class Singleon02 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread01()).start();
}
}
//静态私有属性
private static Singleon02 instance;
//构造器私有化
private Singleon02(){

}
//提供方法访问instance
//加入了同步块,保证了线程的安全,降低了效率
public static synchronized Singleon02 getInstance() {
return null==instance?(new Singleon02()):instance;
// if (instance == null) {
// instance = new Singleon02();
// }
// return instance;
}

}
class Thread01 implements Runnable{
public void run() {
System.out.println(Singleon02.getInstance());
}
}



这里结果为什么不同。。。什么时候能用三元运算符。
...全文
68 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
迟到_啦 2017-12-04
  • 打赏
  • 举报
回复
今天才看到消息,这俩天一直在搞一个小项目,没上线
1楼说的对,不是三目运算符不能用,是你那里写错了,
 return null==instance?(new Singleon02()):instance;


这句话相当于判断:如果instance为空,则new一个匿名Singleon02类,如果instance已经是一个对象,则直接返回该对象(这也是单例模式的关键)
但是 你这样写的话第一次判断的时候肯定为空,然后新建一个Singleon02类匿名对象,然而这个对象是匿名的,你并没有把它赋值给你定义好的用来限制对象个数的静态变量instance,所以instance始终为空,也就意味着每一次判断都重新new一个匿名的Singleon02对象,因此也就出现了循环10次出现了10个不一样的地址值。


我测试过了,把 那一行代码修改一下就可以了
   return null==instance?(instance = new Singleon02()):instance;

逗比123号 2017-12-01
  • 打赏
  • 举报
回复
因为你的三元运算符没有把生成的对象赋值给instance,应该这样 return instance = instance == null ? new Singleon02() : instance;

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧