使用ThreadLocal轻松解决多线程访问

1.ThreadLocal仿代码

package com.tazi.aop;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MyThreadLocal<T> {
    private Map<Thread,T> values=Collections.synchronizedMap(new HashMap<Thread,T>());
    public T get(){
        Thread thread=Thread.currentThread();
        T t=values.get(thread);
        //第一次获取
        if(t==null&& !values.containsKey(thread)){
            t=initValue();
            values.put(thread, t);
            return t;
        }
        return t;
    }
    public T initValue(){
        return null;
    }
    public void set(T t){
        Thread thread=Thread.currentThread();
        values.put(thread, t);
    }
   
}

 

2.使用的例子

package com.tazi.aop;


public class ResourceQ {
    private int count;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
    public void addCount(){
        count++;
    }
   
}

3.

package com.tazi.aop;


public class ThreadLocalResourceQ {
    private static final MyThreadLocal resourceQ=new MyThreadLocal();
    public static ResourceQ getCurResourceQ(){
        ResourceQ rQ=(ResourceQ)resourceQ.get();
        if(rQ==null){ //说明当前线程还没有改局部变量的副本
            rQ=new ResourceQ();
            resourceQ.set(rQ);//把rQ放到当前线程中。
        }
        return rQ;
    }
}

 

posted @ 2012-01-04 09:25  tazi  阅读(258)  评论(0编辑  收藏  举报