[英]How to get value of variable assigned inside a thread?
我有下面的示例代碼。 變量alpha在線程內部定義。 如何在線程外獲取該變量的變量?
...
new Thread() {
public void run() {
...
String alpha = "new value";
...
...
}
}.start();
...
System.out.println(alpha); // <- how to make this work?
您可以將結果存儲在字段中。 您的問題尚不清楚,代碼是采用非靜態方法還是靜態方法,因此我使用static
方法編寫了一個示例,並將字段相應地設為static
。 如果是實例方法,則該字段不應為static
。 它必須是volatile
這樣更改才能在主線程中看到。
public class Main {
private static volatile String alpha = null;
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
alpha = "new value";
}
}.start();
while (alpha == null); // We wait until the variable is non-null.
System.out.println(alpha);
}
}
您需要在線程之前聲明alpha:
public class Scratch {
static String alpha;
public static void main(String[] args) throws InterruptedException{
new Thread() {
public void run() {
alpha = "new value";
}
}.start();
Thread.sleep(1000);
System.out.println(alpha);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.