码迷,mamicode.com
首页 > 其他好文 > 详细

论integer是地址传递还是值传递(转)

时间:2017-07-06 16:49:38      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:state   key   out   new   str   ring   zed   地址   interrupt   

原文链接:http://blog.csdn.net/witsmakemen/article/details/46874717

 

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

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

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();
    }
  }
}

那就会有人问了,为什么执行如下代码的时候两次的输出结果是一样的?

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是创建一个新的类,所以这个第二次输出的时候结果是一样的!

private final int value;

其他的包装类也存在这种情况,比如BigDecimal、BigInteger

论integer是地址传递还是值传递(转)

标签:state   key   out   new   str   ring   zed   地址   interrupt   

原文地址:http://www.cnblogs.com/aigeileshei/p/7126941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!