Java Concurrency 简明教程
Java Concurrency - ThreadLocal Class
ThreadLocal 类用于创建线程局部变量,该变量只能被同一线程读写。例如,如果两个线程正在访问对同一 threadLocal 变量有引用的代码,那么每个线程将看不到其他线程对 threadLocal 变量所做的任何修改。
The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.
ThreadLocal Methods
以下是 ThreadLocal 类中可用的重要方法列表。
Following is the list of important methods available in the ThreadLocal class.
Sr.No. |
Method & Description |
1 |
public T get() Returns the value in the current thread’s copy of this thread-local variable. |
2 |
protected T initialValue() Returns the current thread’s "initial value" for this thread-local variable. |
3 |
public void remove() Removes the current thread’s value for this thread-local variable. |
4 |
public void set(T value) Sets the current thread’s copy of this thread-local variable to the specified value. |
Example
以下 TestThread 程序展示了 ThreadLocal 类的其中一些方法。此处我们使用了两个计数器变量,一个是普通变量,另一个是 ThreadLocal。
The following TestThread program demonstrates some of these methods of the ThreadLocal class. Here we’ve used two counter variable, one is normal variable and another one is ThreadLocal.
class RunnableDemo implements Runnable {
int counter;
ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<Integer>();
public void run() {
counter++;
if(threadLocalCounter.get() != null) {
threadLocalCounter.set(threadLocalCounter.get().intValue() + 1);
} else {
threadLocalCounter.set(0);
}
System.out.println("Counter: " + counter);
System.out.println("threadLocalCounter: " + threadLocalCounter.get());
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo commonInstance = new RunnableDemo();
Thread t1 = new Thread(commonInstance);
Thread t2 = new Thread(commonInstance);
Thread t3 = new Thread(commonInstance);
Thread t4 = new Thread(commonInstance);
t1.start();
t2.start();
t3.start();
t4.start();
// wait for threads to end
try {
t1.join();
t2.join();
t3.join();
t4.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
这将产生以下结果。
This will produce the following result.
Output
Counter: 1
threadLocalCounter: 0
Counter: 2
threadLocalCounter: 0
Counter: 3
threadLocalCounter: 0
Counter: 4
threadLocalCounter: 0
可以看到计数器的值由每个线程增加,而 threadLocalCounter 对于每个线程都保持为 0。
You can see the value of counter is increased by each thread, but threadLocalCounter remains 0 for each thread.