java - 没有封闭的类型实例是可访问的。

标签 java multithreading thread-safety static-methods

这个问题在这里已经有了答案:





Java - No enclosing instance of type Foo is accessible

(7 个回答)


7年前关闭。




整个代码是:

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

导致以下错误:

No enclosing instance of type ThreadLocalTest is accessible. Must qualify the allocation with an enclosing instance of type ThreadLocalTest (e.g. x.new A() where x is an instance of ThreadLocalTest).



核心问题在于:
我想在静态方法中初始化内部类。
这里有两个解决方案:
  • 将内部类设为外部类
  • 使用外部引用,如:
  • new Thread(test.new MyRunnable(test)).start();//Use test object to create new

    最佳答案

    如果换类 MyThread是静态的,你消除了问题:

    public static final class MyThread implements Runnable
    

    由于您的 main()方法是静态的,如果不首先创建封闭类的实例,就不能依赖封闭类的非静态类型或字段。不过,更好的是甚至不需要这样的访问,这是通过使有问题的类成为静态来实现的。

    关于java - 没有封闭的类型实例是可访问的。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471664/

    相关文章:

    java - 连接池

    java - 避免与数据对象重复

    Java:for 循环使用 i

    java - 如何防止连接池在 mongodb 上使用 java 驱动程序关闭?

    java - 如何正确处理线程中断

    multithreading - Delphi线程最佳实践

    java - 连续为多个可变字段赋值的操作是否可以重新排序?

    java - 如何在eclipse中构建基于maven java的项目

    java - 使用 SAAJ 使用经过身份验证的 Web 服务?

    C 线程在访问非共享资源时给出垃圾输出