Java并发编程:深入剖析ThreadLocal

时间:2022-08-28 18:00:59
有多年编程经验的软件行业艺术家们应该都知道ThreadLocal。ThreadLocal很多地方叫做线程本地变量,也有些地方叫做线程本地存储。通俗的讲ThreadLocal可以让创建的变量只被同一个线程进行读和写操作。
所以尽管有两个线程同时执行一段相同的代码,而且这段代码都指向同一个ThreadLocal变量的引用,但是这两个线程依然不能看到彼此的ThreadLocal变量域。
ThreadLocal提供以下四个方法
public T get() { }//获取当前线程存储在ThreadLocal的值
public void set(T value) { }//设置当前线程往ThreadLocal存储值
public void remove() { }//移除当前线程往ThreadLocal存储值
protected T initialValue() { }//一个protected方法,一般是用来在使用时进行重写的,它是一个延迟加载方法

接下来介绍怎样使用ThreadLocal; 1.创建一个ThreadLocal对象。如以下代码:
    private ThreadLocal threadLocal = new ThreadLocal();

  2.向ThreadLocal对象中设置当前线程变量值:
   ThreadLocal.set("now Thread:"+Thread.currentThread().getName());

</pre></div><div><span style="white-space:pre"></span></div><div><span style="white-space:pre"></span>3.从ThreadLocal对象中获取当前线程变量值;</div><div><span style="white-space:pre"></span></div><div><span style="white-space:pre"></span><pre name="code" class="java">    System.out.println(threadLocal.get());

4.完整的demo代码:
package com.demo.test;

import java.util.Random;

public class MyThreadLocalTest {
public static final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();

public static void main(String[] args) {
new MyTread().start();
new MyTread().start();
new MyTread().start();
new MyTread().start();
}


}
class MyTread extends Thread implements Runnable {

@Override
public void run() {
int val = (int) (Math.random()*100);
System.out.println("now Thread:" + Thread.currentThread().getName()
+ ";val=" + val);
MyThreadLocalTest.threadLocal.set(val);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("now Thread:" + Thread.currentThread().getName()
+ ";val=" + MyThreadLocalTest.threadLocal.get());
}

}
    5.结果
   
now Thread:Thread-1;val=24
now Thread:Thread-0;val=32
now Thread:Thread-2;val=41
now Thread:Thread-3;val=45
now Thread:Thread-1;val=24
now Thread:Thread-0;val=32
now Thread:Thread-2;val=41
now Thread:Thread-3;val=45