gpt4 book ai didi

Java:更改调用线程的变量

转载 作者:行者123 更新时间:2023-11-30 06:22:48 25 4
gpt4 key购买 nike

我有以下代码:

public class Shell {
String status;
Runtime rtime;
Process process;

public void runCmd(final String cmd,String status) throws Exception{
this.status = status;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
process = rtime.exec(cmd);
process.waitFor();
this.status = "check out done";
} catch (IOException e) {

} catch (InterruptedException e) {

}
}
});

t.start();

}

}

但 java 不允许我更改新线程 t 中的 status 变量。可能我需要某种线程间通信。我是线程新手,请告诉我该怎么做这个。

最佳答案

在您的情况下,表达式 this.status 中的 this 引用未定义状态字段的 Runnable 对象。尝试使用 Shell.this.status 而不是 this.status

关于Java:更改调用线程的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com