同步机制是为了同步多个线程对相同资源的并发访问,是为了多个线程之间进行通信的有效方式。
而ThreadLocal是隔离多个线程的数据共享,从根本上就不在多个线程之间共享资源(变量),这样当然不需要对多个线程进行同步了
所以ThreadLocal并不能替代同步机制,两者面向的问题领域不同。
如果你需要进行多个线程之间进行通信,则使用同步机制;如果需要隔离多个线程之间的共享冲突,可以使用ThreadLocal
ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
线程类
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
public
class TestClient extends Thread { private
SequenceNumber sn; public
TestClient(SequenceNumber sn) { this .sn = sn; } @Override public
void run() { for ( int
i =0;i<3;i++) { System. out .println(Thread.currentThread().getName()+ " " +sn.getNextNum()); } } } |
1 |
测试类 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 |
public
class SequenceNumber { private
static ThreadLocal<Integer> seqNum = new
ThreadLocal<Integer>() { public
Integer initialValue() { return
0; }; }; public
int getNextNum() { seqNum. set (seqNum. get ()+1); return
seqNum. get (); } public
static void main(String[] args) { SequenceNumber sn = new
SequenceNumber(); TestClient t1 = new
TestClient(sn); TestClient t2 = new
TestClient(sn); TestClient t3 = new
TestClient(sn); t1.start(); t2.start(); t3.start(); } } |
Java ThreadLocal 学习,布布扣,bubuko.com
原文:http://www.cnblogs.com/brucetie/p/3578833.html