Java中ThreadLocal的使用

Java架构师交流群:793825326

java版本:jdk1.8

IDE:idea 18

写两个个测试类:

public class Entity {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;
}
public class Test {
    Entity entity=new Entity();
    public void start() {
        try {
            entity.setName(Long.toString(Thread.currentThread().getId()));
            System.out.println(Thread.currentThread().getId() + "start");
            Thread.sleep(5000);
            System.out.println("打印线程:"+entity.getName());
            System.out.println(Thread.currentThread().getId() + "end");
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

写一段测试代码:

Test t=new Test();
try {
    Thread thread1= new Thread(() ->  t.start());
    thread1.start();
    Thread.sleep(100);
    Thread thread2= new Thread(() ->  t.start());
    thread2.start();
}
catch (Exception ex)
{
    System.out.println(ex);
}

执行结果:

14start
15start
打印线程:15
14end
打印线程:15
15end

修改原来Test类如下:

public class Test {
    ThreadLocal entity=new ThreadLocal<>();
    public void start() {
        try {
            entity.set(new Entity());
            entity.get().setName(Long.toString(Thread.currentThread().getId()));
            System.out.println(Thread.currentThread().getId() + "start");
            Thread.sleep(5000);
            System.out.println("打印线程:"+entity.get().getName());
            System.out.println(Thread.currentThread().getId() + "end");
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

代码执行结果变为:

14start
15start
打印线程:14
14end
打印线程:15
15end

当公共的变量使用ThreadLocal包装后,每个线程在使用它的时候,会拷贝一个副本,其实是另外一个对象,和其他线程的不再是一个对象了,其原理就是每个线程维护一个ThreadLocalMap,这个类是静态内部类,在ThreadLocal外部拿不到。这样,每个线程都有自己的拷贝,也就不会相互影响了。

 

你可能感兴趣的:(Java中ThreadLocal的使用)