【问题标题】:does java thread have to invoke stopjava线程是否必须调用停止
【发布时间】:2016-02-18 13:47:17
【问题描述】:

我有一个启动线程的按钮,我用它来显示我的系统正在处理。 使用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();
  }
};

【问题讨论】:

  • 确切的错误信息是什么
  • 您应该按照stackoverflow.com/help/mcve 中解释的方式提供您的代码。
  • JDialog - 对我来说就像摇摆一样。如果您正在运行调用组件方法的线程,则它必须在 UI 线程上下文中运行。尝试通过SwingUtilities.invokeLater(Runnable)invokeAndWait(Runnable) 运行您的线程

标签: java multithreading


【解决方案1】:

Thread.currentThread().stop();是@Deprecated JavaDoc

试试下面的

Thread.currentThread().interrupt();

private volatile boolean stopRequested = false;

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

public void requestStop() {
  stopRequested = true;
}

【讨论】:

    【解决方案2】:

    我的观察:

    1. 您正在 UI 线程上调用 Thread.currentThread().stop() 本身,删除这一行
    2. thread2没用,删除吧
    3. 通过SwingUtilities.invokeLater(thread1)调用线程1
    4. 您正在启动两个线程,但您无法确定哪个线程会先运行。我现在不记得 Swing 这么好,但如果先处理对话框然后调用 setVisible(true) 会做一些好事,我会感到惊讶

    【讨论】:

    • 我有在thread2中运行的代码,我只是没有把它复制到这里。如果我想保留 thread2 并且我还想显示对话框并在 thread2 完成运行后自动关闭,有什么建议吗?或者有什么方法可以结合吗?
    • 我会先启动thread2,然后调用join()。如果它有一些与组件相关的操作,则通过SwingUtilities.invokeAndWait() 调用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多