threadlocal实例及原理
所属分类 java
浏览量 1461
ThreadLocal
线程局部变量 线程本地变量
每一个线程都有一份变量的副本 互相不影响 空间换时间
public class ThreadLocalDemo {
static ThreadLocal threadLocalSeq = new ThreadLocal() {
@Override
protected Integer initialValue() {
return 0;
}
};
public static void main(String[] args) throws Exception {
for (int i = 0; i < 3; i++) {
MyThread t = new MyThread();
t.setName("mythread" + i);
t.start();
}
}
private static class MyThread extends Thread {
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("sleep error," + e);
}
int seq = threadLocalSeq.get();
System.out.println(Thread.currentThread().getName() + ":" + seq);
threadLocalSeq.set(seq + 1);
}
System.out.println(Thread.currentThread().getName()+" done!");
}
}
}
ThreadLocal实现原理
public void set(T value) {
Thread t = Thread.currentThread();
// 获取线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
// map为空,创建
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
完整例子代码
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/ThreadLocalDemo.java
上一篇
下一篇
单体应用vs微服务
nacos介绍
nacos Java客户端使用
使用int作为key的IntHashMap
netty高性能要点
redis要点整理