多线程 - 10.线程副本

ThreadLocal 线程副本的使用

线程副本类主要解决的就是,要每个单独的线程,都绑定自己线程内部共享的值,可以想象每个线程都有自己的 ThreadLocal 笔记本,这个笔记本上记载着所有该线程自身的共享变量

class MyThreadLocal{
    private ThreadLocal<String> myThreadLocal = new ThreadLocal<>();
    public void setSomething() {
        myThreadLocal.set("xxx");
    }
    public String getSomething() {
        return myThreadLocal.get();
    }
}

class ThreadA extends Thread{

    @Override
    public void run() {
        super.run();
        MyThreadLocal myThreadLocal = new MyThreadLocal();
        myThreadLocal.setSomething();
        System.out.println("Thread a get" + myThreadLocal.getSomething());
    }

}
class ThreadB extends Thread{

    @Override
    public void run() {
        super.run();
        System.out.println("Thread b get" + new MyThreadLocal().getSomething());
    }
}

public class test0 {
    public static void main(String[] args) {
        Thread a = new ThreadA();
        Thread b = new ThreadB();
        a.start();
        b.start();
    }
}

Thread b getnull
Thread a getxxx

set() , get() , remove() , initialValue() , 这 4 个函数属于 ThreadLocal 线程副本最为常用的函数。

InheritableThreadLocal 线程副本的使用

InheritableThreadLocal 继承于 ThreadLocal 。

class MyThreadLocal extends InheritableThreadLocal<String>{
    @Override
    protected String initialValue() {
        return "my initialValue";
    }
}

class MyTools{
    static public MyThreadLocal myThreadLocal = new MyThreadLocal();
}

class ThreadA extends Thread{
    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 3; i++) {
            System.out.println("ThreadA 从 MyThreadLocal 中取到的值:" + MyTools.myThreadLocal.get());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class test0 {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            System.out.println("Main 从 MyThreadLocal 中取到的值:" + MyTools.myThreadLocal.get());
            Thread.sleep(1000);
        }

        Thread.sleep(5000);

        Thread a = new ThreadA();
        a.start();
    }
}

Main 从 MyThreadLocal 中取到的值:my initialValue
Main 从 MyThreadLocal 中取到的值:my initialValue
Main 从 MyThreadLocal 中取到的值:my initialValue
ThreadA 从 MyThreadLocal 中取到的值:my initialValue
ThreadA 从 MyThreadLocal 中取到的值:my initialValue
ThreadA 从 MyThreadLocal 中取到的值:my initialValue

你可能感兴趣的:(Java)