从头认识多线程-2.1 局部变量与实例变量的线程安全

这一章节我们来讨论一下局部变量与实例变量的线程安全。

1.结论

局部变量线程安全的

实例变量不是线程安全的


2.代码清单

package com.ray.deepintothread.ch02.topic_1;

public class ThreadSafeOfLocalVariable {
	public static void main(String[] args) throws InterruptedException {
		ThreadOne threadOne = new ThreadOne();
		Thread thread = new Thread(threadOne);
		Thread thread1 = new Thread(threadOne);
		thread.start();
		thread1.start();
	}
}

class ThreadOne implements Runnable {

	@Override
	public void run() {
		int count = 0;
		for (int i = 0; i < 5; i++) {
			System.out.println(count++);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

输出:

0
0
1
1
2
2
3
3
4
4


从输出可以看出,count在++的时候没有被另一个线程篡改,因此,局部变量是线程安全的


package com.ray.deepintothread.ch02.topic_1;

public class ThreadSafeOfInstanceVariable {
	public static void main(String[] args) throws InterruptedException {
		ThreadFour threadFour = new ThreadFour();
		Thread thread = new Thread(threadFour);
		Thread thread1 = new Thread(threadFour);
		thread.start();
		thread1.start();
	}
}

class ThreadFour implements Runnable {
	private int count = 0;

	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println(count++);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

输出:

0
0
1
2
3
4
5
6
7
8


我们来观察输出结果,可以看到从第四个结果开始,其实两个线程之间就开始互相篡改,而且输出结果看上去是无序的,因此输出结果跟上面的完全不一样

但是,当我们在run上面加上同步标识符,他的输出结果将会变成有序的

package com.ray.deepintothread.ch02.topic_1;

public class ThreadSafeOfInstanceVariable {
	public static void main(String[] args) throws InterruptedException {
		ThreadTow threadTow = new ThreadTow();
		Thread thread = new Thread(threadTow);
		Thread thread1 = new Thread(threadTow);
		thread.start();
		thread1.start();
	}
}

class ThreadTow implements Runnable {
	private int count = 0;

	private synchronized void test() {
		for (int i = 0; i < 5; i++) {
			System.out.println(count++);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {
		test();
	}
}

输出:

0
1
2
3
4
5
6
7
8
9


总结:这一章节主要讲述了局部变量与实例变量的线程安全。


这一章节就到这里,谢谢

------------------------------------------------------------------------------------

我的github:https://github.com/raylee2015/DeepIntoThread


目录:http://blog.csdn.net/raylee2007/article/details/51204573


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值