在两个线程和主程序之间共享对象 [英] Sharing an object between two threads and main program
问题描述
我是Java的新手,我正在参加并发编程课程。我拼命地试图获得一个最小的工作示例,可以帮助演示概念,我学到了像使用'synchronized'关键字和跨线程共享对象。
一直在搜索,但不能得到一个基本框架。 Java程序员,亲切的帮助。
I am new to Java and I'm attending a Concurrent Programming course. I am desperately trying to get a minimal working example that can help to demonstrate concepts I have learnt like using 'synchronized' keyword and sharing an object across threads. Have been searching, but could not get a basic framework. Java programmers, kindly help.
推荐答案
这里是一个非常好的例子在两个线程之间共享数组。通常你会看到所有的零,但有时会出现螺旋,你看到其他数字。
Here is a very shot example of sharing an array between two threads. Usually you will see all zeros, but sometimes things get screwy and you see other numbers.
final int[] arr = new int[100];
Thread one = new Thread() {
public void run() {
// synchronized (arr) {
for (int i = 0; i < arr.length * 100000; i++) {
arr[i % arr.length]--;
}
// }
}
};
Thread two = new Thread() {
public void run() {
// synchronized (arr) {
for (int i = 0; i < arr.length * 100000; i++) {
arr[i % arr.length]++;
}
//}
}
};
one.start();
two.start();
one.join();
two.join();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
$ b < c $ c>在循环周围,你将总是看到打印输出中的所有 0
。如果取消注释同步块,代码将运行没有错误。
But, if you synchronize on arr
around the looping you will always see all 0
s in the print out. If you uncomment the synchronized block, the code will run without error.
这篇关于在两个线程和主程序之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!