现在的问题来了,当我们关注例子I,希望共享类RunInstance,即
RunInstance t = new RunInstance();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
却又要对变量进行线程单独化的管理时,怎么办?这时候就有了ThreadLocal。请看
例子III
首先我们对类TestInstance做一下改造,也就是把Flag变成ThreadLocal,即线程的独自变量
改造如下1,2,3点,接着我们仍旧运行例子I
class TestInstance {
static Integer count = 0;
//1: public int flag = 0;
public ThreadLocal flag = new ThreadLocal(){
public Integer initialValue(){
return 0;
}
};