Java线程 - 线程的本地变量

Ell*_*ott 2 java thread-safety

我正在努力理解java线程的工作,所以请原谅这个相当简单的问题.

假设我有一个包含N个线程的程序.每个线程在字符串数组的不同部分上执行相同的指令.我们通过一个带有runnable接口的类来调用线程.出于这个例子的目的,让我们说它是这样的:

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 */
    }
}
Run Code Online (Sandbox Code Playgroud)

最后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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的问题:线程的"theWord"和"Z"变量是本地的,还是它们在线程中共享,因此可能会发生线程冲突.如果是后者,如何最好地保护这些变量.

谢谢你帮助一个困惑的人.

埃利奥特

Enn*_*oji 7

局部变量在堆栈上分配,并且是线程的本地变量.只有成员字段跨线程共享.因此,theWord并且Z不会跨线程共享,您不必担心冲突.

鉴于String是不可变的,我们在方法countLeters()中对线程安全的唯一关注是访问globalArray.

现在,如果构造这个数组"发生在 - 之前"访问globalArray,只要没有线程"写入"globalArray,代码就是安全的.

"发生之前"关系可以通过多种方式强制执行(通过使用synchronized关键字,final关键字,volatile关键字,使用java.util.concurrent库等).