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,这样就可以避免多线程并发的问题。
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,这样就可以避免多线程并发的问题。
相关文章推荐
- Appium+java代码实现上/下/左/右滑动
- iOS之网上下载数据的两种方式
- leetcode.149. Max Points on a Line
- Logstash之关系型数据库(mysql或oracle)数据入ElasticSearch
- jQuery学习笔记五:选择器集合
- apache
- AppWidget实现机制分析--应用更新时更新AppWidget深入分析
- dell 交换机 双链路冗余
- hdoj--3605--Escape(状态压缩+最大流)
- mysql-5.7.12-winx64安装教程
- TNS-00510 IBM/AIX RISC System/6000 Error: 11: Resource temporarily unavailable
- SQLite 常用函数
- Android 编程下 Touch 事件的分发和消费机制
- Android的文件系统结构
- ABP(http://www.aspnetboilerplate.com/)下载初始化
- ztree插件简单使用
- C++ 成员运算符(. 和 ->)
- IOS属性修饰符总结
- sulime text 3
- solution Of 1029. Median (25)