这个在java中的threadlocal类可以保证使你创建的变量只能被相同的线程读和写。因此,甚至如果两个线程正在执行相同的代码,并且这个代码有一个对于threadlocal变量的引用,然后这两个线程就不能看到彼此的threadlocal变量。
创建一个threadlocal
这里有一个代码现实如何创建一个threadlocal:
private threadlocal mythreadlocal = new threadlocal();
正如你看到的,你实例化一个新的threadlocal对象。这个每个线程只需要做一次。甚至如果不同的线程执行访问一个threadlocal的相同的代码,每一个线程将只会看到它自己的threadlocal实例。甚至如果两个线程设置不同的值在这相同的threadlocal对象上,它们都不会看到彼此的值。
访问一个threadlocal
一旦一个threadlocal被创建了,你就可以像下面这样设置一个值去存储:
mythreadlocal.set("a thread local value");
你可以像下面这样去读这个值:
string threadlocalvalue = (string) mythreadlocal.get();
这个get方法返回一个对象,并且这个set方法传递一个对象作为参数。
泛型化的threadlocal
你可以创建一个泛型化的threadlocal,以至于你不用在调用get方法的时候进行强制转化了。这里有一个例子:
private threadlocal<string> mythreadlocal = new threadlocal<string>();
现在你只能存储存储字符串类型在threadlocal实例中。另外的,你不需要强制转化这个值了:
mythreadlocal.set("hello threadlocal");
string threadlocalvalue = mythreadlocal.get();
初始化threadlocal值
因为设置一个threadlocal对象的值只是对于设置这个值的线程可见的,所以没有线程可以使用set方法设置threadlocal的值对所有的线程可见。
代替的,你可以通过子类threadlocal特指一个初始化的值对于一个threadlocal对象,以及覆盖initialvalue方法。像下面这样:
private threadlocal mythreadlocal = new threadlocal<string>() {
@override protected string initialvalue() {
return "this is the initial value";
}
};
现在所有的线程可以看到相同的初始化值,在调用set方法之前。
完整的threadlocal实例
这里有一个完整运行的threadlocal实例
public class threadlocalexample {
public static class myrunnable implements runnable {
private threadlocal<integer> threadlocal =
new threadlocal<integer>();
@override
public void run() {
threadlocal.set( (int) (math.random() * 100d) );
try {
thread.sleep(2000);
} catch (interruptedexception e) {
}
system.out.println(threadlocal.get());
}
}
public static void main(string[] args) {
myrunnable sharedrunnableinstance = new myrunnable();
thread thread1 = new thread(sharedrunnableinstance);
thread thread2 = new thread(sharedrunnableinstance);
thread1.start();
thread2.start();
thread1.join(); //wait for thread 1 to terminate
thread2.join(); //wait for thread 2 to terminate
}
}
这个例子创建了一个单独的myrunnable实例,它被传递给了两个不同的线程。这两个线程都执行了run方法,并且在threadlocal实例上设置了不同的值。如果对于这个set方法的调用访问是同步的,并且它还没有使用threadlocal对象,第二个线程将会覆盖第一个线程设置的值。
然而,因为它是一个threadlocal对象,不能看到彼此的值。因此,他们设置和得到不同的值。
inheritablethreadlocal
这个inheritablethreadlocal类是threadlocal类的子类。代替的每一个线程在一个threadloca内部都有它自己的值,这个类同意访问对于一个线程的值,并且被那个线程创建的所有子线程。
以上就是java本地线程(threadlocal)的内容。