整个代码是:
public class ThreadLocalTest {
ThreadLocal<Integer> globalint = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return new Integer(0);
}
};
public class MyThread implements Runnable{
Integer myi;
ThreadLocalTest mytest;
public MyThread(Integer i, ThreadLocalTest test) {
myi = i;
mytest = test;
}
@Override
public void run() {
System.out.println("I am thread:" + myi);
Integer myint = mytest.globalint.get();
System.out.println(myint);
mytest.globalint.set(myi);
}
}
public static void main(String[] args){
ThreadLocalTest test = new ThreadLocalTest();
new Thread(new MyThread(new Integer(1), test)).start();
}
}
为什么下面的片段:
ThreadLocalTest test=new ThreadLocalTest();
new Thread(new MyThread(new Integer(1),test)).start();
导致以下错误:
无法访问 ThreadLocalTest 类型的封闭实例。必须使用 ThreadLocalTest 类型的封闭实例来限定分配(例如 xnew A(),其中 x 是 ThreadLocalTest 的实例)。
核心问题是:我想在静态方法中初始化内部类。这里有两个解决方案:
使内部类成为外部类
使用外部参考,如:
new Thread(test.new MyRunnable(test)).start();//Use test object to create new