4

スレッドローカル変数を使用すると、各スレッドは変数のローカル コピーを取得します。私の最初の質問は、各スレッドが変数を変更した場合、変更された値はそのローカル コピーにのみ残るのでしょうか? それとも、ある時点で「グローバル変数」も更新しようとし、同時実行の問題が発生しますか?

私のもう1つの質問は、メソッドで変数を宣言すると、独自のスタックでメソッドを実行する各スレッドが独自のコピーを取得することです。メソッドレベル変数を宣言することは、それをスレッドローカルにすることと同じですか?

4

4 に答える 4

3

最初の質問: 各スレッドは threadlocal 変数のコピーを更新します。グローバルな状態はスレッド間で共有されません。

2 番目の質問: ローカル変数を宣言すると、threadlocal と同様に動作します。すべてのスレッドには独自のコピーがありますが、別のメソッドなどでグローバルにアクセスすることはできません。このような場合に、threadlocal が便利です。

于 2013-08-29T14:09:04.710 に答える
1

ThreadLocal<T>オブジェクトを参照する最も簡単な方法は、 として参照することです。この場合Map<Thread, T>、呼び出しは、基になるThreadLocal#get()を呼び出して適切な値を検索します。これは実際の実装ではありませんが、最も簡単な方法であることに注意してください。Map#get(Thread.currentThread())Map

ThreadLocal変数は、同時に複数のスレッドから実際にアクセスできるメンバーとしてのみ役立ちます。メソッド内の変数のローカル宣言は、ローカルであるため、他のスレッドからアクセスすることはできません。「同じ」とは言いませんが、どちらもスレッドセーフです。

一般的な使用法は、シングルトン オブジェクトのインスタンス メンバー変数、またはマルチスレッド環境でのクラスの静的メンバー変数です。

ほとんどの場合、サーブレット環境でリクエスト コンテキスト情報を渡すために使用されます。

于 2013-08-29T14:06:51.593 に答える
1

If i use a threadlocal variable, then each thread gets a local copy of the variable

I think there is some cunfusion regarding the term local copy of the variable. There is no copy. Every thread gets its own variable; these are independant of each other. It doesn't mean, however, that they cannot hold a reference to a shared object. So, just using threadlocal variables alone does not save you from concurrency issues.

Regarding your second question: No. Local variables and threadlocal variables are different. Local variables are not accessible outside the block in which they are defined. Therefore, for example, calling the same method twice will result in a different value each time. On the other hand, threadlocal variables keep their values as long as the thread exists.

Basically, threadlocal variables are kind of 'static' variables for one single thread.

于 2013-08-29T14:11:00.067 に答える