【问题标题】:No enclosing instance of type is accessible. [duplicate]没有封闭的类型实例是可访问的。 [复制]
【发布时间】:2012-09-10 09:38:14
【问题描述】:

整个代码是:

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

为什么是下面的 sn-p:

ThreadLocalTest test=new ThreadLocalTest();
    new Thread(new MyThread(new Integer(1),test)).start();

导致以下错误:

没有可以访问 ThreadLocalTest 类型的封闭实例。必须符合条件 使用 ThreadLocalTest 类型的封闭实例进行分配(例如 x.new A() 其中 x 是 ThreadLocalTest 的一个实例)。


核心问题是: 我想在静态方法中初始化内部类。 这里有两个解决方案:

  1. 将内部类设为外部类

  2. 使用外部引用,如:

new Thread(test.new MyRunnable(test)).start();//Use test object to create new

【问题讨论】:

  • 什么错误?我看起来你刚刚将代码重新粘贴为错误

标签: java multithreading thread-safety static-methods


【解决方案1】:

由于MyThread 是一个内部类,您必须使用MyThreadTest 的实例来访问它:

public static void main(String args[]) {
    MyThreadTest test = new MyThreadTest();
    new Thread(test.new MyThread(new Integer(1),test)).start();
}

【讨论】:

    【解决方案2】:

    如果将MyThread 类更改为static,则问题消除:

    public static final class MyThread implements Runnable
    

    由于您的 main() 方法是静态的,因此您不能在不首先创建封闭类的实例的情况下依赖封闭类的非静态类型或字段。不过,更好的是甚至不需要此类访问,这是通过将相关类设为静态来实现的。

    【讨论】:

      猜你喜欢
      • 2013-09-12
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 2018-05-12
      • 2013-02-17
      • 2011-12-15
      • 2016-11-20
      相关资源
      最近更新 更多