10年 Java程序员,硬核人生!勇往直前,永不退缩!

欢迎围观我的git:https://github.com/R1310328554/spring_security_learn 寻找志同道合的有志于研究技术的朋友,关注本人微信公众号: 觉醒的码农,或Q群 165874185

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 示例:

import java.io.Serializable;

public class TestThreadLocal implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -1279921928557717157L;

    int age;

    public static void main(String[] argv) throws Exception {

        TestThreadLocal tt = new TestThreadLocal();

        Testthread t1 = new Testthread(tt);
        Testthread t2 = new Testthread(tt);
        Testthread t3 = new Testthread(tt);

        t1.start();
        t2.start();
        t3.start();

    }

     static int ii = 0;
//    static Integer ii = 0;

    // public Integer getIi() {// 这个方式不行
    // ii ++;
    // return ii;
    // }

    public Integer getIi() {
        // tl.set( ii ++ ); // 这个方式也不行, 必须要下面的方式。
        tl.set(tl.get() + 1);
        return tl.get();
    }

    /**
     * { } 内部的初始化是必须的。  否则出现 nullpointexception 
     */
    ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
        protected Integer initialValue() {
            ii = 0;
            return ii;
        };
    };

}

class Testthread extends Thread {

    TestThreadLocal ttl;

    public Testthread(TestThreadLocal ttl) {
        this.ttl = ttl;
    }

    @Override
    public void run() {
        String name2 = Thread.currentThread().getName();
        for (int i = 0; i < 3; i++) {
            System.out.println(" name " + name2 + ttl.getIi());
        }
    }
}

 

ThreadLocal 的作用在于,将某些变量绑定到线程中去, 提供一种,线程安全的方式操作某些变量。

posted on 2017-05-31 11:37  CanntBelieve  阅读(199)  评论(0编辑  收藏  举报