java线程必须调用stop

时间:2016-02-18 13:47:18

标签: java multithreading

我有一个启动线程的按钮,用于显示我的系统正在处理。 与thread1我打开一个jdialog并显示我的系统正在运行。我使用thread2dlg.dispose();关闭我的jdialog 我的问题是,一旦我的程序停止运行,我再次单击该按钮,然后出现一条错误消息,告诉我我的线程有问题。

我有另一个没有线程的按钮,如果我再次点击它,它会完美地执行动作。

有人可以告诉我问题出在哪里吗?我尝试使用Thread.currentThread().stop();关闭该主题,但它仍无法正常工作。

这是我的示例代码,

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        if(chooser == null){
           String message = "No file chosen. Please choose your file.";
        JOptionPane.showMessageDialog(new JFrame(), message, "WiresharkHelper",
        JOptionPane.ERROR_MESSAGE); 
        }
        else if(chooser != null){
        jTabbedPane4.setSelectedIndex(1);
        thread1.start();
        thread2.start();
        }
    }
JOptionPane opt = new JOptionPane("Application is running", JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{});//I put this in global for my thread2 to dispose my dialog
    JDialog dlg = opt.createDialog("Warning");
    Thread thread2 = new Thread () {
  public void run () {
        dlg.setVisible(true);
  }
};
    Thread thread1 = new Thread () {
  public void run () {
    //code running
    dlg.dispose();
  }
};

2 个答案:

答案 0 :(得分:0)

Thread.currentThread()停止();是@Deprecated JavaDoc

尝试以下

Thread.currentThread().interrupt();

private volatile boolean stopRequested = false;

public void run() {
  while (!stopRequested) {
    ...
  }
}

public void requestStop() {
  stopRequested = true;
}

答案 1 :(得分:0)

我的观察:

  1. 您正在UI线程上调用Thread.currentThread().stop() 本身,删除此行
  2. thread2没用,删除它
  3. 通过SwingUtilities.invokeLater(thread1)
  4. 调用thread1
  5. 你正在开始两个线程而你无法说,哪个会首先运行。我现在不记得Swing了,但是如果先处理对话然后调用setVisible(true)会做些好事我会感到惊讶
相关问题