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
B:B:0
B:B:1
A:A:1
B:B:2
A:A:2
A:A:3
B:B:3
A:A:4
B:B:4
A:A:5
B:B:5
A:A:6
B:B:6
A:A:7
B:B:7
A:A:8
B:B:8
B:B: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注意:子线程取值的时候主线程将值进行更改,子线程读到的还是旧值。
推荐阅读
-
python类中super()和__init__()的区别
-
iOS开发中关键字const/static/extern、UIKIT_EXTERN的区别和用法
-
详谈Array和ArrayList的区别与联系
-
浅析java中print和println的区别
-
基于Java中throw和throws的区别(详解)
-
大家需要掌握的 html下SPAN和DIV的区别
-
IE6,IE7和firefox对DIV的支持区别
-
iOS中containsString和rangeOfString的区别小结
-
简单谈谈c/c++中#import、#include和@class的区别
-
MySQL中REPLACE INTO和INSERT INTO的区别分析