package cn.liz.threaddemo;
// ThreadLocal 与 绑定 解决同一个线程内的数据共享问题
// 将数据拷贝一份到线程中 ,因此 线程 之间的数据互不影响
public class ThreadLocalTest {
private static ThreadLocal<Computer> local = new ThreadLocal<Computer>();
public static void main(String[] args) {
for(int i = 0;i<2;i++){
new Thread(){
public void run(){
// 生生成一个随机数
int price = (int)(Math.random()*100);
System.out.println(Thread.currentThread().getName()+"-->"+price);
Computer c = new Computer();
c.setPrice(price);
c.setBrand("lenovo"+Thread.currentThread().getName());
local.set(c);
First.test();
Second.test();
}
}.start();
}
}
static class First{
public static void test(){
Computer com = local.get();
if(com==null){
System.out.println("-------");
}else{
System.out.println("first->"+
Thread.currentThread().getName()+
"->"+com.getBrand()+
com.getPrice());
}
}
}
static class Second{
public static void test(){
Computer com = local.get();
if(com==null){
System.out.println("-------");
}else{
System.out.println("Second->"+
Thread.currentThread().getName()+
"->"+com.getBrand()+
com.getPrice());
}
}
}
}
结果:
Thread-0-->14
Thread-1-->25
first->Thread-1->lenovoThread-125.0
first->Thread-0->lenovoThread-014.0
Second->Thread-1->lenovoThread-125.0
Second->Thread-0->lenovoThread-014.0
由此可见:
ThreadLocal将数据分别拷贝到各个线程中,各个线程都持有数据的一份拷贝,彼此之间互不影响。
ThreadLocal 与线程 挂钩。