ThreadLocal类原理及测试用例

main线程类:

public class DemoThreadLocal {
    public static void main(String[] args) {
        ThreadLocal<String> tl = new ThreadLocal<>();

        //获取当前main线程对象绑定的值
        String s = tl.get();
        System.out.println(s);  //null

        //给当前main线程对象绑定值
        tl.set("hello ThreadLocal");
        String s1 = tl.get();
        System.out.println(s1); //hello ThreadLocal

        //开启一个新线程
        SubThread subThread = new SubThread(tl);
        subThread.start();
    }
}

subThread线程类:

public class SubThread extends Thread {
    private ThreadLocal<String> tl;

    public SubThread(ThreadLocal tl){
        this.tl = tl;
    }

    @Override
    public void run() {
        //获取当前线程对象上绑定的值
        String s = tl.get();
        System.out.println("当前线程对象绑定的值:"+s);    //当前线程对象绑定的值:null

        tl.set("芜湖");
        String s1 = tl.get();
        System.out.println("当前线程对象绑定的值:"+s1);   //当前线程对象绑定的值:芜湖
    }
}

 

posted @ 2020-08-28 21:40  硬盘红了  阅读(147)  评论(0编辑  收藏  举报