如果你定义了一个单实例的java bean,它有若干属性,但是有一个属性不是线程安全的,比如说HashMap。并且碰巧你并不需要在不同的线程中共享这个属性,也就是说这个属性不存在跨线程的意义。那么你不要sychronize这么复杂的东西,ThreadLocal将是你不错的选择。

举例来说:

package threadlocal;

import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class TreadLocalTest { static ThreadLocal<TreeMap<String, Integer>> map0 = new ThreadLocal<TreeMap<String, Integer>>() {
@Override
protected TreeMap<String, Integer> initialValue() {
System.out.println(Thread.currentThread().getName() + ":initialValue");
return new TreeMap<String, Integer>();
}
}; public void run() {
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 3; i++) {
es.execute(new Task(i));
}
es.shutdown();
} public static class Task implements Runnable {
private int id; public Task(int id) {
this.id = id;
} public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":start");
TreeMap<String, Integer> map = map0.get();
for (int i = 0; i < 5; i++) {
map.put(threadName + ":" + i, i + id * 100);
try {
Thread.sleep(100);
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ':' + map);
}
} public static void main(String[] args) {
TreadLocalTest test = new TreadLocalTest();
test.run();
} }

输出解释;

pool-1-thread-1:start
pool-1-thread-1:initialValue
pool-1-thread-2:start
pool-1-thread-2:initialValue
pool-1-thread-3:start
pool-1-thread-3:initialValue
pool-1-thread-1:{pool-1-thread-1:0=0, pool-1-thread-1:1=1, pool-1-thread-1:2=2, pool-1-thread-1:3=3, pool-1-thread-1:4=4}
pool-1-thread-2:{pool-1-thread-2:0=100, pool-1-thread-2:1=101, pool-1-thread-2:2=102, pool-1-thread-2:3=103, pool-1-thread-2:4=104}
pool-1-thread-3:{pool-1-thread-3:0=200, pool-1-thread-3:1=201, pool-1-thread-3:2=202, pool-1-thread-3:3=203, pool-1-thread-3:4=204}

可以看到map0 虽然是个静态变量,但是initialValue被调用了三次,通过debug发现,initialValue是从map0.get处发起的。而且每个线程都有自己的map,虽然他们同时执行。

进入Theadlocal代码,可以发现如下的片段;

public T get() { 
        Thread t = Thread.currentThread(); 
        ThreadLocalMap map = getMap(t); 
        if (map != null) { 
            ThreadLocalMap.Entry e = map.getEntry(this); 
            if (e != null) 
                return (T)e.value; 
        } 
        return setInitialValue(); 
    }

这说明ThreadLocal确实只有一个变量,但是它内部包含一个map,针对每个thread保留一个entry,如果对应的thread不存在则会调用initialValue。

http://www.cnblogs.com/alphablox/archive/2013/01/20/2869061.html

package threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /*2015-9-15*/
public class KeepObjectStatus { private int times = -1; public int getTimes() {
return times;
} public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Task(2));
executor.execute(new Task(5));
executor.shutdown();
} public void process() {
if (times < 10) {
times++;
}
} public static ThreadLocal<KeepObjectStatus> instance = new ThreadLocal<KeepObjectStatus>() { @Override
protected KeepObjectStatus initialValue() {
System.out.println(Thread.currentThread() + " begin to init");
return new KeepObjectStatus();
} }; } class Task implements Runnable { private int step; public Task(int step) {
super();
this.step = step;
} @Override
public void run() { KeepObjectStatus kos = KeepObjectStatus.instance.get();
for (int i = 0; i < 10; i += step) {
kos.process();
System.out.println(String.format("%s==> Step:%s %d", Thread.currentThread(), step, kos.getTimes()));
}
} }

Output:

Thread[pool-1-thread-1,5,main]  begin to init
Thread[pool-1-thread-2,5,main] begin to init
Thread[pool-1-thread-2,5,main]==> Step:5 0
Thread[pool-1-thread-1,5,main]==> Step:2 0
Thread[pool-1-thread-2,5,main]==> Step:5 1
Thread[pool-1-thread-1,5,main]==> Step:2 1
Thread[pool-1-thread-1,5,main]==> Step:2 2
Thread[pool-1-thread-1,5,main]==> Step:2 3
Thread[pool-1-thread-1,5,main]==> Step:2 4

ThreadLocal用法和实现原理(转)的更多相关文章

  1. ThreadLocal用法和实现原理

    如果你定义了一个单实例的java bean,它有若干属性,但是有一个属性不是线程安全的,比如说HashMap.并且碰巧你并不需要在不同的线程中共享这个属性,也就是说这个属性不存在跨线程的意义.那么你不 ...

  2. java.lang.ThreadLocal的作用和原理?列举在哪些程序中见过ThreadLocal的使用?

    java.lang.ThreadLocal的作用和原理?列举在哪些程序中见过ThreadLocal的使用? 说明类java.lang.ThreadLocal的作用和原理.列举在哪些程序中见过Threa ...

  3. ThreadLocal及InheritableThreadLocal的原理剖析

    我们知道,线程的不安全问题,主要是由于多线程并发读取一个变量而引起的,那么有没有一种办法可以让一个变量是线程独有的呢,这样不就可以解决线程安全问题了么.其实JDK已经为我们提供了ThreadLocal ...

  4. ThreadLocal的使用及原理分析

    文章简介 ThreadLocal应该都比较熟悉,这篇文章会基于ThreadLocal的应用以及实现原理做一个全面的分析 内容导航 什么是ThreadLocal ThreadLocal的使用 分析Thr ...

  5. ThreadLocal系列(一)-ThreadLocal的使用及原理解析

    ThreadLocal系列之ThreadLocal(源码基于java8) 项目中我们如果想要某个对象在程序运行中的任意位置获取到,就需要借助ThreadLocal来实现,这个对象称作线程的本地变量,下 ...

  6. 在spring+beranate中多数据源中使用 ThreadLocal ,总结的原理 --费元星

    设计模式 首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问 ...

  7. ThreadLocal的使用及原理解析

    # 基本使用 JDK的lang包下提供了ThreadLocal类,我们可以使用它创建一个线程变量,线程变量的作用域仅在于此线程内.<br />用2个示例来展示一下ThreadLocal的用 ...

  8. 多线程爬坑之路-ThreadLocal源码及原理的深入分析

    ThreadLocal<T>类:以空间换时间提供一种多线程更快捷访问变量的方式.这种方式不存在竞争,所以也不存在并发的安全性问题. This class provides thread-l ...

  9. Spring Boot的Listener机制的用法和实现原理详解

    之前在介绍了在spring-boot启动过程中调用runner的原理,今天我们介绍另外一种可以实现相似功能的机制:spring-boot的Listener机制. 通过注册Listener,可以实现对于 ...

随机推荐

  1. 第10季asp.net基础

    什么是ASP.Net: ASP.Net是一种动态网页技术,在服务器端运行.Net代码,动态生成HTML.可以使用javascript.Dom在浏览器端完成很多工作,但是有很多工作无法在浏览器端完成,比 ...

  2. MBProgressHUD简单使用

    使用HUD最多的情形用于请求等待提示 例如做登录的时候在确认登陆的时候可以用HUD提示正在登陆. 最基本的使用 初始化 //self.view代表在哪个view中显示hud MBProgressHUD ...

  3. js的初始化

    在项目中遇到了类似于这样的js, myinit.js文件: var wyl_01 = { tip : function(msg){ alert('i am a tip,msg:'+msg); }, t ...

  4. day1作业脚本

    1.编写登录接口: - 输入用户名和密码 - 认证成功后显示欢迎信息 - 输错三次后锁定 2.编写多级菜单 - 三级菜单 - 可依次进入子菜单 第一次写python脚本,因为没有学到函数,所以写的有点 ...

  5. [LeetCode]题解(python):019-Remove Nth Node From End of List

    题目来源: https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 题意分析: 这道题是给定一个链表,删除倒数第n个节点.提醒, ...

  6. graph isomorphism 开源算法库VFlib, Nauty

    VFlib 开源算法库网站:http://www.cs.sunysb.edu/~algorith/implement/vflib/implement.shtml Nauty 开源算法库网站:http: ...

  7. BZOJ 1828

    program bzoj1828; ; check=; type node=record l,r,s,a:longint; end; ..maxn*] of node; a,b,c:..maxn] o ...

  8. Linux malloc大内存的方法

    本博文为原创,遵循CC3.0协议,转载请注明出处:http://blog.csdn.net/lux_veritas/article/details/9963199 ------------------ ...

  9. 通过SecureCRT和PuTTY连接臻云CentOS版云主机

    原文地址:http://jingyan.baidu.com/article/fa4125acb6648128ac7092dc.html 如何通过SecureCRT和PuTTY工具远程连接臻云CentO ...

  10. USACO Prime Palindromes 构造回文数

    这道题目一点也不卡素数的判断 就是朴素的sqrt(n) 也不卡 所以~放心的用吧. 构造回文的时候看了HINT 其中是这么写的: Generate palindromes by combining d ...