java ThreadLocal的使用

类ThreadLocal主要解决的就是每个线程绑定自己的值.

package com.test;

public class TestThreadLocal {
    
    public static ThreadLocal<String> t1 = new ThreadLocal<>();
    
    public void setLocalData(String value) {
        t1.set(value);
    }
    
    public void printLocalData() {
        System.out.println(Thread.currentThread().getName() + ":" + this.t1.get());
    }
    
    public static void main(String[] args) {
        TestThreadLocal local = new TestThreadLocal();
        Thread t1 = new Thread(new Runnable() {
            
            @Override
            public void run() {
                local.setLocalData("testA");
                local.printLocalData();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            
            @Override
            public void run() {
                local.printLocalData();
            }
        });
        t1.start();
        t2.start();
    }
}
结果:
Thread-0:testA
Thread-1:null
原文地址:https://www.cnblogs.com/gouge/p/9120405.html