您的位置:首页 > 编程语言 > Java开发

java Thread之ThreadLocal(线程局部变量)

2012-06-05 09:26 302 查看
ThreadLocal即线程局部变量。

功能:为每个使用该变量的线程,提供一个该变量的副本。

其实ThreadLocal中拥有一个Map,它是线程->变量的映射。

主要方法有三个,set,get,initValue。

set与get的作用不用多讲,主要是initValue,它默认返回的是null,子类可以通过重载该方法,来改变默认值。

1 public void set(T value) {

2 Thread t = Thread.currentThread();
3 ThreadLocalMap map = getMap(t);
4 if (map != null)
5 map.set(this, value);
6 else
7 createMap(t, value);
8 }
9

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();
}

protected T initialValue() {
return null;
}

使用示例:

1 package com.cody.test.thread;
2
3 public class ThreadLocalTest {
4
5 private static ThreadLocal<String> mThreadLocal = new ThreadLocal<String>();
6 private static Business business = new Business();
7 public static void main(String[] args) {
8 new Thread(new Runnable() {
9
@Override
public void run() {
business.sub();
}
}).start(); //开始一个线程

business.main();
}

public static class Business{

public void sub(){
for(int i = 0;i < 10;i ++){
mThreadLocal.set(String.valueOf(i));
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : " + mThreadLocal.get());
}
}

public void main(){
for(int i = 0;i < 20;i ++){
mThreadLocal.set(String.valueOf(i));
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : " + mThreadLocal.get());
}
}
}
46 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: