ThreadLocal下

传送门:http://www.nowcoder.com/discuss/18817?type=0&order=0&pos=6&page=0
仔细分析就可以发现,线程之间共享的static变量无法保证线程安全。
那么如何保证线程安全呢?
先看另一种实现:
public class TestB implements Sequence{
    private static ThreadLocal<Integer> numberContainer=new Threadlocal<Integer>(){
            protected Integer initialValue(){
                        return 0;
                        }
                };
    public int getNumber(){
    numberContainer.set(numberContainer.get()+1);
        return numberContainer.get();  }  public static void main(String[] args){ TestB squenceB=new Clinet();
    Client thread1=new Clinet(squenceB);
    Client thread2=new Clinet(squenceB);
    Client thread3=new Clinet(squenceB);
    thread1.start();
    thread2.start();
    thread3.start();
    }
}
解决了
三个线程输出的都是
1
2
3
#Java工程师#
全部评论
今天发帖数达上限了,这里补充下自己实现的ThreadLocal 先看下ThreadLocal的API public void set(T value) 将值放入线程局部变量 public T get() 从线程局部变量获取值 public void remove() 从线程局部变量移除值,JVM垃圾回收 protected T initialValue() 返回线程局部变量中的初始值,默认为null 其实仔细想想,ThreadLocal其实就是封装了Map 废话不多说,上代码 public class MyThreadLocal<T>{ //Collections.synchronizedMap同步     private Map<Thread,T> container=Collections.synchronizedMap(new HashMap<Thread,T>()); //设置值     public void set(T value){         container.put(Thread.currentThread(),value); } //获取值  public T get(){     Thread thread=Thread.currentThread(); T value=container.get(thread); if(value==null && !container.containsKey(thread)){     value=initialValue();     container.put(thread,value); } return value; } //移除 public void remove(){     container.remove(Thread.currentThread()); } //默认值 protected T initialValue(){ return null; } } 手酸了~下次再写了...
点赞 回复 分享
发布于 2016-11-10 14:20
我觉得threadlocal不能保证线程安全,只能保证线程间互不影响。一般用来绑定与线程相关的参数,例如spring的事务管理。
点赞 回复 分享
发布于 2016-11-10 20:13

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务