public void taskInProgress(String jobMessage) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
runningTask = true;
Test:
while (runningTask) {
for (int i = 0; i < runningStars.length; i++) {
System.out.print(runningStars[i].concat(" ").concat(jobMessage));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t.start();
}
public void taskFinnished(String msg) {
this.runningTask = false;
System.out.println("\r".concat(ok(msg)));
}
希望的效果是,星星在控制台中打印为无限进度条,即嵌套在 while
循环中的 for
循环,当我调用在一种方法中,星星被状态和消息取代,然后它们就停止了。我通过在 taskFinnished()
中锁存类字段 runningTask
来实现这一点。
我的问题是,即使在打破 while
循环之后,星星仍然会打印到控制台。即使在 while
循环条件返回 false 后,循环仍会继续执行好几秒钟。
屏幕截图:
如此处所示,在调用 taskFinnished()
方法并且 while 循环中断后,它仍然显示正在提取 tar 存档
。
以下是使用这些实现的代码:
tc.taskInProgress("Extracting tar archive");
// do long operation on main thread, keep console animation running in seperate thread, and return exit int, Unix style
if (exit == 0) {
tc.taskFinnished("Tar finished without errors");
// This breaks the while loop, but more stuff gets printed even after breaking loop
} else {
// failed, handle it
}
最佳答案
尝试更换
for (int i = 0; i < runningStars.length; i++)
与
for (int i = 0; i < runningStars.length && runningTask; i++)
关于java - 通过主线程中的单独方法更改条件后,单独线程中的 while 循环继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389074/