java - 匿名线程类无法访问非静态实例变量

标签 java multithreading concurrency static

我正在尝试访问 Thread 匿名类中的实例变量。我在这里收到一个错误,说要使其静态。这里的要点是,如果我可以访问匿名类中的“this”关键字,并将其视为当前对象持有者,那么为什么它不能以非静态方式访问实例变量。

public class AnonymousThreadDemo {
    int num;

    public AnonymousThreadDemo(int num) {
        this.num = num;
    }

    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                System.out.println("Anonymous " + num); // Why cant we access num instance variable
                System.out.println("Anonymous " + this); // This can be accessed in a nonstatic way
            }
        };
        thread.start();
    }
}

最佳答案

num 是一个非静态字段,它属于一个特定的实例。您不能直接在 static main 中引用它,因为可以在不创建实例的情况下调用 static 方法。

this实际上引用了thread,它是一个局部变量,当你执行run时,thread必须已创建。

如果您尝试在 main 中引用 AnonymousThreadDemo.this,您将得到相同的结果:

public static void main(String[] args) {
    Thread thread = new Thread() {

        @Override
        public void run() {
            System.out.println("Anonymous " + AnonymousThreadDemo.this); // compile error
        }
    };
    thread.start();
}
<小时/>

这样就可以了,你可以在局部类中引用局部变量:

public static void main(String[] args) {
    int num = 0;

    Thread thread = new Thread() {
        @Override
        public void run() {
            System.out.println("Anonymous " + num);
        }
    };
    thread.start();
}
<小时/>

没关系,您可以在其方法中引用非静态局部类字段:

public static void main(String[] args) {
    Thread thread = new Thread() {
        int num = 0;

        @Override
        public void run() {
            System.out.println("Anonymous " + num);
        }
    };
    thread.start();
}
<小时/>

检查this了解更多。

关于java - 匿名线程类无法访问非静态实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146785/

相关文章:

java - ThreadPoolExecutor 关闭 API 文档措辞 "does not wait"

java - JBehave 故事参数示例

Java 字节缓冲区到 C

java - AtomicReader 和 KNearestNeighbour train() 方法

c++ - 在多线程 C++ 程序中使用 std::vector 时应用程序崩溃

python - sqlobject线程安全

java - java.lang.Math.max(int a, int b) 线程安全吗?

java - 如何设置SWT Tree的高度?

java多线程未利用所有核心

java - 在线程之间传递可变数据