首先说一下线程:
Thread-> 一个人,Runnable->一个任务
每次有任务,只需要将任务交给人来做,使用start()进行开始就行。
ThreadLocal 方法:
- void set(T value):保存值;
- T get():获取值;
- void remove():移除值
实例代码
@Test
public void func1() throws InterruptedException {
ThreadLocal<String> tl=new ThreadLocal<>();
//存
tl.set("hello");
//取
System.out.println(Thread.currentThread().getName()+":"+tl.get());
new Thread(){
@Override
public void run() {
//在子线程中取
System.out.println(Thread.currentThread().getName()+":"+tl.get());
}
}.start();
Thread.sleep(1000);
//删
tl.remove();
}
结果:
main:hello
Thread-0:null
ThreadLocal 解析
ThreadLocal 内部是一个map,其中值是当前线程对象,也就是说不同的线程只能获取自身的值
key | value |
thread0 | aaa |
thread1 | bbb |
核心代码:
class ThreadLocal<T>{
private Map<Thread,T> map=new HashMap<Thread,T>();
//存
public void set(T date){
map.put(Thread.currentThread(),date);
}
//取
public T get(){
return map.get(Thread.currentThread());
}
//删
public void remove(){
map.remove(Thread.currentThread());
}
}