线程不会停止

时间:2014-04-19 23:11:40

标签: java multithreading jframe

我有一个运行线程的程序,当我单击退出按钮(自定义)时,我告诉线程停止,然后处理JFrame。但线程一直在运行;将我的CPU提高到100%; 每次我点击一个按钮,时钟就会打开。这是打开它的代码。

new ClockGui().main();

ClockGui是时钟,它是我的包中的一个单独的.java文件,其中包含一个单独的主.java文件。

另外,如果它有帮助,我注意到每次单击按钮时我的CPU都会上升50%,当我关闭JFrame时,ClockGui就是,我的CPU瘫痪减少25%。这仍然增加了25%。所以我猜测问题出在主.java文件中;也许我怎么称呼ClockGui?

public boolean running = true;
...
private void exitButtonMouseClicked(java.awt.event.MouseEvent evt) { //this is the event that happens when I click the exit button                                     
        running = false;
        this.dispose(); //this closes the JFrame
}
public class myThread extends Thread {
        @Override
        public void run() {
            while(running) {
                ...
            }
        }
    }

JFrame按预期关闭,但我的CPU仍然是100%。我是否正确关闭了线程?我该如何解决我的问题?我希望线程停止。

1 个答案:

答案 0 :(得分:7)

volatile变量不能保证传播到其他线程(立即,及时或根本不传播),尤其是在HotSpot优化发生时。可能,running = false被视为死囚并被忽视。

您应将running声明为:

public volatile boolean running = true;