threadlocal
类用于创建只能由同一个线程读取和写入的线程局部变量。 例如,如果两个线程正在访问引用相同threadlocal
变量的代码,那么每个线程都不会看到任何其他线程操作完成的线程变量。
以下是threadlocal
类中可用的重要方法的列表。
编号 | 方法 | 描述 |
---|---|---|
1 | public t get() |
返回当前线程的线程局部变量的副本中的值。 |
2 | protected t initialvalue() |
返回此线程局部变量的当前线程的“初始值”。 |
3 | public void remove() |
删除此线程局部变量的当前线程的值。 |
4 | public void set(t value) |
将当前线程的线程局部变量的副本设置为指定的值。 |
以下testthread
程序演示了threadlocal
类的上面一些方法。 这里我们使用了两个计数器(counter
)变量,一个是常量变量,另一个是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");
}
}
}
这将产生以下结果 -
counter: 1
threadlocalcounter: 0
counter: 2
threadlocalcounter: 0
counter: 4
counter: 3
threadlocalcounter: 0
threadlocalcounter: 0
您可以看到变量(counter
)的值由每个线程增加,但是threadlocalcounter
对于每个线程都保持为0
。