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

 

posted @ 2018-06-01 10:20  L狗哥  阅读(124)  评论(0编辑  收藏  举报