【发布时间】: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