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

java-线程-用ThreadLocal类实现线程范围内的数据共享

2011-10-06 20:04 661 查看
代码如下,比较坑爹,就是上一篇文章的hashmap改为了ThreadLocal

public class ThreadScopeShareData {

/**
* @param args
*/
//	private static HashMap<Thread, Integer> map = new HashMap<Thread, Integer>();
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread() +" data is "+data);
//					map.put(Thread.currentThread(), data);
threadLocal.set(data);
new A().get();
new B().get();
}
}).start();

}

}

static class A{
public void get(){
int data = threadLocal.get();//map.get(Thread.currentThread());
System.out.println("A get data:" + data + " from " + Thread.currentThread().getName());
}
}

static class B{
public void get(){
int data = threadLocal.get();//map.get(Thread.currentThread());
System.out.println("B get data:" + data + " from " + Thread.currentThread().getName());
}
}

}


运行结果一样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: