繁体   English   中英

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

[英]Anonymous thread class not able to access non static instance variables

我正在尝试访问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是一个non static字段,它属于特定实例。 您不能直接在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();
}

检查这个更多。

num是非静态的,这意味着它将在内存中的静态main之后。 因此,当main将尝试指向num ,它将在内存中不可用,即。 它仍然不会被宣布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM