ThreadLocal
变量值的共享可以使用public static变量形式,类ThreadLocal主要解决的就是每个线程绑定自己的值。
隔离性
类ThreadLocal解决的是变量在不同线程间的隔离性,也就是不同线程拥有自己的值,不同线程中的值是可以放入ThreadLocal类进行保存的
Java例子1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55public class Tool {
public static ThreadLocal threadLocal=new ThreadLocal();
}
public class ThreadA extends Thread{
public void run() {
for (int i = 0; i <5 ; i++) {
Tool.threadLocal.set(i);
System.out.println("ThreadA get Value=" + Tool.threadLocal.get());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadB extends Thread {
public void run() {
for (int i = 0; i <5 ; i++) {
Tool.threadLocal.set(i);
System.out.println("ThreadB get Value=" + Tool.threadLocal.get());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Run {
public static void main(String[] args) {
ThreadA threadA=new ThreadA();
threadA.start();
ThreadB theadB =new ThreadB();
theadB.start();
for (int i = 0; i <5 ; i++) {
Tool.threadLocal.set(i);
System.out.println("MainThread get Value=" + Tool.threadLocal.get());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果:
1 | ThreadA get Value=0 |
initialValue方法设置初始值
类ThreadLocal 可以在main线程和其他线程里设置初始值
Java例子:
1 | public class Tools { |
结果:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15ThreadC线程中取值=1545141944675
在Mian线程中取值=1545141944675
ThreadC线程中取值=1545141944675
在Mian线程中取值=1545141944675
ThreadC线程中取值=1545141944675
ThreadC线程中取值=1545141944675
在Mian线程中取值=1545141944675
ThreadC线程中取值=1545141944675
在Mian线程中取值=1545141944675
在Mian线程中取值=1545141944675
在Mian线程中取值=1545141944675
在Mian线程中取值=1545141944675
在Mian线程中取值=1545141944675
在Mian线程中取值=1545141944675
在Mian线程中取值=1545141944675