【问题标题】:Anonymous thread class not able to access non static instance variables匿名线程类无法访问非静态实例变量
【发布时间】:2018-05-03 04:04:12
【问题描述】:

我正在尝试访问 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();
    }
}

【问题讨论】:

    标签: java multithreading concurrency static


    【解决方案1】:

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

    查看this了解更多信息。

    【讨论】:

    • 我将 this 关键字与 main class 混淆了。感谢这些例子:)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 2015-02-18
      相关资源
      最近更新 更多