简体   繁体   English

在运行期间无法停止线程,但正在调试

[英]Can't stop a thread during running but debugging

I tried to implement an automatic rolling progress-bar. 我试图实现一个自动滚动进度条。 The problem is that I can't stop it onece it starts. 问题是,一旦启动我就无法停止它。 But It works fine when during the step by step debugging, and only during the debugging. 但是,在逐步调试过程中,并且仅在调试过程中,它可以正常工作。

Here's a fragment of my codes. 这是我的代码片段。 Any help will be highly appreciated. 任何帮助将不胜感激。

package test;

import javax.swing.*;

public final class MyTest{
private boolean isvisible = false;
private JProgressBar progressbar = new JProgressBar();
/**
 * thread of automatic rolling progress-bar
 */
private Thread proT = new Thread(new Runnable(){
    @Override
    public void run(){
    isvisible = true;
    progressbar.setVisible(true);
    while(true){
        progressBar.setValue((progressBar.getValue() + 20)%100);
        System.out.println(progressBar.getValue()); 
        try{
        Thread.sleep(500);
        }catch(InterruptedException e){
        e.printStackTrace();
        }
        if(!isvisible){
        progressbar.setVisible(false);
        break;
        }
    }
    }
});
/**
 * constructor
 */
public MyTest(){
    //initiate GUI
}
/**
 * show an automatic rolling progress-bar
 */
public void showProgressBar(){
    proT.start();
}

/**
 * stop/veil the progress-bar
 */
public void veilProgressBar(){
    isvisible = false;
}
}

There are a whole raft of problems here: 这里有很多问题:

  1. You are doing Swing GUI updates from not on the EDT Thread. 您正在通过不在EDT线程上进行Swing GUI更新。

  2. Your isvisible variable is not volatile so changes made from one thread may not be seen from another. 您的isvisible变量不是可变的,因此从一个线程进行的更改可能不会从另一个线程看到。

  3. While(true) sleep in a thread is generally bad design. 虽然(true)在线程中睡眠通常是错误的设计。

You should use a SwingTimer here with a schedule to call back every X to do the update. 您应该在此处使用带有时间表的SwingTimer来回调每个X进行更新。 When you need to stop the update just cancel the SwingTimer and hide the control. 当您需要停止更新时,只需取消SwingTimer并隐藏控件即可。 The hide needs to be done from the EDT too though so you may need to do SwingUtilities.invokeLater . 尽管也需要从EDT中进行隐藏,所以您可能需要执行SwingUtilities.invokeLater

There may be more too but that's what I've seen so far. 可能还有更多,但这是我到目前为止所看到的。

AFAIK isvisible variable should be at least volatile for other threads to be able to notice that it's been changed. 据我所知可见性变应至少volatile其他线程能够发现它已经改变了。 You do no synchronization whatsoever so the value doesn't get updated. 您不执行任何同步操作,因此不会更新该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM