Note

春蚕到死丝方尽,人至期颐亦不休,一息尚存须努力,留作青年为范畴。

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

 用途

当前线程的存储信息,每个线程独享. 比如用户浏览访问的节点信息,保证访问节点与存储节点的一致.

代码:

下面用一个简单的案例来说明怎么使用ThreadLocal

package fx;

/**
 * 线程存储工具类
 * @author lxz
 *
 */
public class UserThreadLocalUtil {
    
    private static ThreadLocal<Integer> t1 = new ThreadLocal<Integer>();//存储年龄
    private static ThreadLocal<String> t2 = new ThreadLocal<String>();//存储姓名

    public static ThreadLocal<Integer> getT1() {
        return t1;
    }

    public static void setT1(ThreadLocal<Integer> t1) {
        UserThreadLocalUtil.t1 = t1;
    }

    public static ThreadLocal<String> getT2() {
        return t2;
    }

    public static void setT2(ThreadLocal<String> t2) {
        UserThreadLocalUtil.t2 = t2;
    }

    public static void main(String[] args) {
        Runnable thread1 = new Runnable() {

            public void run() {
                UserThreadLocalUtil.getT1().set(18);
                UserThreadLocalUtil.getT2().set("小明");
                while(true){
                    System.out.println(UserThreadLocalUtil.getT1().get());
                    System.out.println(UserThreadLocalUtil.getT2().get());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Runnable thread2 = new Runnable() {

            public void run() {
                UserThreadLocalUtil.getT1().set(20);
                UserThreadLocalUtil.getT2().set("小红");
                while(true){
                    System.out.println(UserThreadLocalUtil.getT1().get());
                    System.out.println(UserThreadLocalUtil.getT2().get());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread tt1 = new Thread(thread1);
        Thread tt2 = new Thread(thread2);
        tt1.start();
        tt2.start();
    }
}

测试结果:

18
小明
20
小红
18
小明
20
小红
18
20
小红
小明

通过结果发现,即使调用的是static的工具类,两个线程获取的值互相不干扰.

 

posted on 2016-02-25 15:30  'Note'  阅读(238)  评论(0编辑  收藏  举报