论integer是地址传递还是值传递

论integer是地址传递还是值传递

Integer 作为传参的时候是地址传递,可以参考如下例子,在程序刚启动的时候把 Integer 的index 对象锁住 ,并且调用了 wait方法,释放了锁的资源,等待notify,最后过了5秒钟,等待testObject 调用notify 方法就继续执行了。大家都知道锁的对象和释放的对象必须是同一个,否则会抛出 java.lang.IllegalMonitorStateException 。由此可以证明 Integer作为参数传递的时候是地址传递,而非值传递。

Java代码 收藏代码
public class IntegerSyn {

public static void main(String[] args) throws InterruptedException {  
    Integer index = 0;  
    TestObject a = new TestObject(index);  
    synchronized (index) {  
        new Thread(a).start();  
        index.wait();  
    }  
    System.out.println("end");  
}  

}

class TestObject implements Runnable {
private Integer index;

public TestObject(Integer index){  
    this.index = index;  
}  

public void run() {  
    try {  
        TimeUnit.SECONDS.sleep(5);  
    } catch (InterruptedException e) {  
        e.printStackTrace();  
    }  
    synchronized (index) {  
        index.notify();  
    }  
}  

}

那就会有人问了,为什么执行如下代码的时候两次的输出结果是一样的?
Java代码 收藏代码
public static void main(String[] args) throws InterruptedException {
Integer index = 0;
System.out.println(index);
test(index);
System.out.println(index);
}

public static void  test(Integer index){  
    index++;  
}  

理由很简单,可以看到 Integer 类中final的value字段,说明一旦integer类创建之后他的值就不能被修改,在 index++ 的时候Integer是创建一个新的类,所以这个第二次输出的时候结果是一样的!
Java代码
private final int value;

原文地址:http://cheng-xinwei.iteye.com/blog/2162232?utm_source=tuicool&utm_medium=referral

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值