局部变量的线程安全性

局部变量是线程安全的,这句话正确,但是也不够准确,关键在于如何理解局部变量。
通常都是通过栈帧对线程的私有性,而局部变量是保存在栈帧中的,来解释这句话的正确性。

如果局部变量是基本类型,那么这句解释没有问题,正如下面的例子,虽然 local 变量被所有的线程访问,但是初始化后,再去改变它,编译器会报错,这就使其成为了事实上的 final 变量,而被 final 修饰的基本类型变量是线程安全的。

	public static void test() {
		
		double local = 100.0;
		
		for (int i = 0; i < 10; i++) {

			double local1 = local + i;

			System.out.println(System.identityHashCode(local) + " " + local + " " + Thread.currentThread().getName());
			System.out.println(System.identityHashCode(local1) + " " + local1 + " " + Thread.currentThread().getName());
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					
					System.out.println(System.identityHashCode(local) + " " + local + " " + Thread.currentThread().getName());
					System.out.println(System.identityHashCode(local1) + " " + local1 + " " + Thread.currentThread().getName());
				}
			}).start();
		}

	}

如果局部变量是引用类型,那么尽管局部变量保存的引用地址仍然是不可改变的,是线程安全的,但是这种线程安全性并非我们所关注的重点,此时,该变量所指向的堆变量的线程安全性才是我们所担忧的。如下面的例子,局部对象初始化后仍然是不可重新赋值的,但是该对象的确已经线程逸出了,局部变量 inner 虽然是线程安全的,但是这段代码却不是线程安全的。

	public static void test() {
		
		InnerTest inner = new InnerTest();
		
		for (int i = 0; i < 10; i++) {

			System.out.println(System.currentTimeMillis() + " " + System.identityHashCode(inner) + " " + 
					System.identityHashCode(inner.local) + " " + 
					inner.local + " " + Thread.currentThread().getName() + " before ");
			inner.local = i+0.0;
			System.out.println(System.currentTimeMillis() + " " + System.identityHashCode(inner) + " " + 
					System.identityHashCode(inner.local) + " " + 
					inner.local + " " + Thread.currentThread().getName() + " after ");
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					
					System.out.println(System.currentTimeMillis() + " " + System.identityHashCode(inner) + " " + 
							System.identityHashCode(inner.local) + " " + 
							inner.local + " " + Thread.currentThread().getName()+" before ");
					inner.local  += 100;
					System.out.println(System.currentTimeMillis() + " " + System.identityHashCode(inner) + " " + 
							System.identityHashCode(inner.local) + " " + 
							inner.local + " " + Thread.currentThread().getName() + " after ");
					
				}
			}).start();
		}

	}
	private static class InnerTest {
		Double local = 100.0;
		InnerTest() {
			
		}
	}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值