美文网首页
Java并发 | ThreadLocal类

Java并发 | ThreadLocal类

作者: icebreakeros | 来源:发表于2019-08-08 16:55 被阅读0次

类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());
    }
}

相关文章

网友评论

      本文标题:Java并发 | ThreadLocal类

      本文链接:https://www.haomeiwen.com/subject/manxjctx.html