我有以下示例代码。变量alpha在线程内定义。如何在线程外获取该变量的变量?
...
new Thread() {
public void run() {
...
String alpha = "new value";
...
...
}
}.start();
...
System.out.println(alpha); // <- how to make this work?
答案 0 :(得分:5)
您可以将结果存储在字段中。您的问题不清楚代码是采用非静态还是静态方法,因此我使用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);
}
}
答案 1 :(得分:0)
你需要在线程之前声明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);
}
}