【发布时间】:2011-05-14 04:05:46
【问题描述】:
我很难理解 Java 线程的工作原理,所以请原谅这个相当简单的问题。
假设我有一个包含 N 个线程的程序。每个线程在字符串数组的不同部分执行相同的指令。我们通过具有可运行接口的类调用线程。就本示例而言,假设它是这样的:
run() {
while (startStop = loopGetRange() != null) {
countLetters(startStop.start,startStop.stop);
/* start is the beginning cell in the array where the process starts
and stop is the ending cell in the array where the process stops */
}
}
最后 countLetters 只是一个简单的方法如下:
private void countLeters (int start, int stop) {
for (int y = start; <= stop; y++) {
String theWord = globalArray[y];
int z = theWord.length;
System.out.println("For word "+theWord+" there are "+z+" characters");
}
}
这是我的问题:像“theWord”和“Z”这样的变量是线程本地的,还是它们在线程之间共享,因此可能会发生线程冲突。如果是后者,如何最好地保护这些变量。
感谢您帮助困惑的人。
艾略特
【问题讨论】:
标签: java thread-safety