Java并发 | ThreadLocal类

类ThreadLocal

变量值的共享可以使用public static变量的形式,所有线程都使用同一个public static变量
如果想实现每一个线程都有自己的共享变量该如何解决?JDK中提供了类ThreadLocal正式为了解决这样的问题

实例

class Tools {
    public static ThreadLocal<String> t = new ThreadLocal<>();
}

class A implements Runnable {
    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {
                Tools.t.set(Thread.currentThread().getName() + "-" + (i + 1));
                System.out.println("A: " + Tools.t.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class B implements Runnable {
    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {
                Tools.t.set(Thread.currentThread().getName() + "-" + (i + 1));
                System.out.println("B: " + Tools.t.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Run {

    public static void main(String[] args) throws InterruptedException {
        Thread aThread = new Thread(new A());
        Thread bThread = new Thread(new B());
        aThread.start();
        bThread.start();

        for (int i = 0; i < 100; i++) {
            Tools.t.set(Thread.currentThread().getName() + "-" + (i + 1));
            System.out.println("MAIN: " + Tools.t.get());
            Thread.sleep(200);
        }
    }
}

解决get返回null问题

继承ThreadLocal,重写initialValue方法

class ThreadLocalExt extends ThreadLocal {
    @Override
    protected Object initialValue() {
        return "default value";
    }
}

public class Run {
    public static ThreadLicalExt t = new ThreadLocalExt();

    public static void main(String[] args) {
        if (Optional.ofNullable(t.get()).isEmpty()) {
            System.out.println("no default value");
        }
        System.out.println(t.get());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容