标签:
这一章节我们来讨论一下局部变量与实例变量的线程安全。
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
标签:
原文地址:http://blog.csdn.net/raylee2007/article/details/51213409