标签:
(多线程数据共用的)示例代码:
先来看看“java线程研究---(7)Thread同步:多线程数据共用会产生问题”这篇文章里面主要的代码例子
ShareDataThread.java
package thread; public class ShareDataThread implements Runnable { private int i = 0; @Override public void run() { while (i < 10) { i++; for (int j = 0; j < 10000000l; j++) ; System.out.println(Thread.currentThread().getName() + ": " + i); } } }
package thread; public class OneObjExample { public static void main(String abc[]) { ShareDataThread s1 = new ShareDataThread(); Thread t1 = new Thread(s1); Thread t2 = new Thread(s1); t1.start(); t2.start(); } }
Thread-1: 1
Thread-1: 3
Thread-0: 4
Thread-1: 5
Thread-0: 6
Thread-1: 7
Thread-1: 8
Thread-0: 9
Thread-1: 10
Thread-0: 10
分析运行结果:
我就如上的结果,有如下的分析(或者说猜测,因为多线程这东西,这能根绝现象去揣测,无从得到底这两个线程是如何交替运行的):
package thread; public class ShareDataThread implements Runnable { private int i = 0; @Override public void run() { while (i < 10) { synchronized(this){ // 锁块 i++; for (int j = 0; j < 10000000l; j++); System.out.println(Thread.currentThread().getName() + ": " + i); } } } }
package thread; public class OneObjExample { public static void main(String abc[]) { ShareDataThread s1 = new ShareDataThread(); Thread t1 = new Thread(s1); Thread t2 = new Thread(s1); t1.start(); t2.start(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/miqi770/article/details/48174637