[英]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.