您的位置:首页 > 其它

ThreadLocal使用

2016-05-17 16:15 288 查看
package ThreadLocal;

import java.util.HashMap;

public class ThreadLocalTest {
static ThreadLocal<HashMap> threadLocal = new ThreadLocal<HashMap>(){

//初始化threadlocal
protected HashMap initialValue(){
System.out.println(Thread.currentThread().getName()+ " init");
return new HashMap();
}

};

public void run(){
Thread[] threads = new Thread[3];
for(int i=0;i<threads.length;i++){
threads[i] = new Thread(new T(i));
threads[i].start();
}
}
public class T implements Runnable{
private int index;

public T(int index){
this.index = index;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ " start");

                      //ThreadLocal相当于一个map,获取当前线程的HashMap   //static ThreadLocal<HashMap> threadLocal = new ThreadLocal<HashMap>(){

HashMap map = threadLocal.get();
for(int i=0;i<10;i++){
map.put(i, i+ (index * 100));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " map:"+ map);
}
}
public static void main(String[] args) {

ThreadLocalTest test = new ThreadLocalTest();
test.run();

}

}

//使用ThreadLocal的场景,多线程并发量大的时候,可以考虑使用。

//比如对于时间格式转换的SimpleDateFormat可以启动多个线程,使用SimpleDateFormat,这样就可以避免多线程并发的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: