1
Thread-3 1
Thread-2 2
Thread-3 2
Thread-2 3
Thread-3 3
Process finished with exit code 0
tlt对象是一个,废话tl对象也是一个,因为组合关系是一对一的。但是tl对象内部的Map随着线程的增多,会创建很多Integer对象。只是Integer和int已经通用了。所以感觉不到Integer的对象属性。
二、不用ThreadLocal
假如不用ThreadLocal,只需要将MyThreadLocal类重新定义为:
/**
* 使用了ThreadLocal的类
*
* @author leizhimin 2010-1-5 10:35:27
*/
public class MyThreadLocal {
private Integer t1 = 0;
public Integer getNextNum(){
return t1=t1+1;
}
// //定义了一个ThreadLocal变量,用来保存int或Integer数据
// private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
// @Override
// protected Integer initialValue() {
// return 0;
// }
// };
//
// public Integer getNextNum() {
// //将tl的值获取后加1,并更新设置t1的值
// tl.set(tl.get() + 1);
// return tl.get();
// }
}
然后运行测试:
Thread-2 1
Thread-2 2
Thread-1 4
Thread-1 6
Thread-3 3
Thread-3 9
Thread-3 10
Thread-1 8
Thread-0 7
Thread-0 11
Thread-0 12
Thread-2 5
Process finished with exit code 0
从这里可以看出,四个线程共享了tlt变量,结果每个线程都直接修改tlt的属性。
Java?殻?侮秘ThreadLocal(3)
扮寂:2011-06-22 51cto 匪冫
眉、徭失糞?倖ThreadLocal
package com.lavasoft.test2;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 聞喘阻ThreadLocal議窃
*
* @author leizhimin 2010-1-5 10:35:27
*/
public class MyThreadLocal {
//協吶阻匯倖ThreadLocal延楚?喘栖隠贋int賜Integer方象
private com.lavasoft.test2.ThreadLocal<Integer> tl = new com.lavasoft.test2.ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer getNextNum() {
//繍tl議峙資函朔紗1?旺厚仟譜崔t1議峙
tl.set(tl.get() + 1);
return tl.get();
}
}
class ThreadLocal<T> {
private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>());
public ThreadLocal() {
}
protected T initialValue() {
return null;
}
public T get() {
Threa
|