多个线程共享数据

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package cn.itcast.heima2;

public class MultiThreadShareData {

/**
* 多个线程共享数据
*/
private static ShareData1 data1 = new ShareData1();

public static void main(String[] args) {
ShareData1 data2 = new ShareData1();
new Thread(new MyRunnable1(data2)).start();
new Thread(new MyRunnable2(data2)).start();

final ShareData1 data1 = new ShareData1();
new Thread(new Runnable(){
@Override
public void run() {
data1.decrement();

}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
data1.increment();

}
}).start();

}

}

class MyRunnable1 implements Runnable{
private ShareData1 data1;
public MyRunnable1(ShareData1 data1){
this.data1 = data1;
}
public void run() {
data1.decrement();

}
}

class MyRunnable2 implements Runnable{
private ShareData1 data1;
public MyRunnable2(ShareData1 data1){
this.data1 = data1;
}
public void run() {
data1.increment();
}
}

class ShareData1 /*implements Runnable*/{
/* private int count = 100;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
count--;
}
}*/


private int j = 0;
public synchronized void increment(){
j++;
}

public synchronized void decrement(){
j--;
}
}

总结

一个ThreadLocal只能定义一个变量,多个变量需要多少ThreadLocal,也可将多个变量定义为一个实体,然后定义一个存放该实体的ThreadLocal;将ThreadLocal封装到一个类中(构建一个线程范围内的对象),这样的代码比较优雅。;每个线程结束的时候ThreadLocal会自动收集,除非被其他地方引用。

参考:
http://ifeve.com/java-theadlocal/