欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ThreadLocal和InheritableThreadLocal的区别

程序员文章站 2022-06-21 11:38:27
...

1、ThreadLocal
主要解决每个线程绑定自己的值,达到线程直接隔离。
1.1如果第一次访问没有设定初始值,返回为null
1.2线程直接的隔离性

//继承ThreadLocal类
public class ThreadLocalExt extends ThreadLocal{
}
//创建两个线程,分别设置自己的值
public class ThreadA extends  Thread{
    @Override
    public void run() {
        for(int i = 0; i < 10; i ++){
            Tools.local.set("A:"+ i);
            System.out.println("A:" + Tools.local.get());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadB extends Thread{
    @Override
    public void run() {
        for(int i = 0; i < 10; i ++){
            Tools.local.set("B:"+ i);
            System.out.println("B:" + Tools.local.get());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Tools {
    public static ThreadLocalExt local = new ThreadLocalExt();
}
程序入口类:
public class Run {
    public static void main(String[] args) throws InterruptedException {
        ThreadA t1 = new ThreadA();
        t1.start();
        ThreadB t2 = new ThreadB();
        t2.start();
    }
}

运行结果

A:A:0
BB:0
BB:1
A:A:1
BB:2
A:A:2
A:A:3
BB:3
A:A:4
BB:4
A:A:5
BB:5
A:A:6
BB:6
A:A:7
BB:7
A:A:8
BB:8
BB:9
A:A:9

1.3通过重写initialValue方法可以设置初始化值
2、InheriThreadLocalExt
2.1值继承子线程可以从父线程中取得值。

public class InheriThreadLocalExt  extends InheritableThreadLocal{
    @Override
    protected Object initialValue() {
        return new Date().getTime();
    }
}
public class Tools {
    public static  InheriThreadLocalExt local = new InheriThreadLocalExt();
}
public class ThreadA extends  Thread{
    @Override
    public void run() {
        for(int i = 0; i < 10; i ++){
            System.out.println("A:" + Tools.local.get());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Run {
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 10; i ++){
            System.out.println("Main方法中获取" + Tools.local.get());
        }
        ThreadA t1 = new ThreadA();
        t1.start();
    }
}

运行结果:

Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
Main方法中获取1494859232485
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492
A:1494859232492

2.2注意:子线程取值的时候主线程将值进行更改,子线程读到的还是旧值。

相关标签: Thread 线程