ThreadLocal 使用

2016-10-31  本文已影响39人  持续进步者

ThreadLocal是什么

ThreadLocal为解决多线程程序的并发问题提供一种新的思路。
使用这个工具类可以很简洁地编写出有优美的多线程程序

ThreadLocal 有什么用

ThreadLocal如何用

代码示例
//不使用 ThreadLocal
 class TestNum{
    private int num =0;
    public int getNextNum() {
        return num++;
    }   
}

class TestCLient extends Thread {
    private TestNum testNum;

    public TestCLient(TestNum testNum) {
        this.testNum = testNum;
    }

    @Override
    public void run() {
        super.run();
        for(int i=0;i<3;i++) {
            System.out.println("thread[" + Thread.currentThread().getName()
                    + "]  -------> i=" + testNum.getNextNum());
        }
        
    }

}

TestNum testNum = new TestNum();
TestCLient t1 = new TestCLient(testNum);
TestCLient t2 = new TestCLient(testNum);
TestCLient t3 = new TestCLient(testNum);
t1.start();
t2.start();
t3.start();

输出结果:
    thread[Thread-1]  -------> i=1
    thread[Thread-0]  -------> i=1
    thread[Thread-0]  -------> i=3
    thread[Thread-2]  -------> i=0
    thread[Thread-2]  -------> i=5
    thread[Thread-2]  -------> i=6
    thread[Thread-0]  -------> i=4
    thread[Thread-1]  -------> i=2
    thread[Thread-1]  -------> i=7
每个线程的i都会被污染 

//使用 ThreadLocal
 class TestNum2{
    private   ThreadLocal<Integer> tl = new ThreadLocal<Integer>();
    public int getNextNum() {
        Integer a = tl.get();
        if(a == null) {
            System.out.println("a == "+ Thread.currentThread().getName());
            a =0;
            tl.set(a);
        }
        tl.set(++a);
            
        return tl.get();
    }   
} 

输出结果:
a == Thread-0
thread[Thread-0]  -------> i=1
thread[Thread-0]  -------> i=2
thread[Thread-0]  -------> i=3
a == Thread-2
thread[Thread-2]  -------> i=1
thread[Thread-2]  -------> i=2
thread[Thread-2]  -------> i=3
a == Thread-1
thread[Thread-1]  -------> i=1
thread[Thread-1]  -------> i=2
thread[Thread-1]  -------> i=3

每个线程的i都会是局部变量其他线程不会污染

2016.10.31

上一篇 下一篇

猜你喜欢

热点阅读