java - 通过主线程中的单独方法更改条件后,单独线程中的 while 循环继续运行

标签 java multithreading

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 后,循环仍会继续执行好几秒钟。

屏幕截图:

enter image description here

如此处所示,在调用 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/

相关文章:

java - Scanner.next() 不阻塞

ios - 如何在获取歌曲列表的所有 Persistent ID 和 Assets URL 时防止设备挂起?

c - 如何在工作流树中表示 fork() && fork()?

android - 我的广播接收器未在多线程应用程序中注册

java - 如何中断这个runnable

java - 需要哪个类来指定encodeByte()方法?

java - 检索 jtextfield 数据以与单击的复选框一起使用

java - 哪种设计模式或缓存策略适合这种模式?

java - 在 NetBeans 中暂停 while 循环,直到按下确认按钮

c# - 带有等待异步和线程的C#控制流