首页 > 其他 > 详细

Java ThreadLocal 学习

时间:2014-03-04 09:51:50      阅读:438      评论:0      收藏:0      [点我收藏+]

同步机制是为了同步多个线程对相同资源的并发访问,是为了多个线程之间进行通信的有效方式。

而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();
    }
     
}
参考资料:http://www.blogjava.net/Ericzhang5231/articles/JavaThreadlocal.html

Java ThreadLocal 学习,布布扣,bubuko.com

Java ThreadLocal 学习

原文:http://www.cnblogs.com/brucetie/p/3578833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!