java线程必须调用stop吗
我有一个启动线程的按钮,我用它来显示我的系统正在处理。 使用java线程必须调用stop吗,java,multithreading,Java,Multithreading,我有一个启动线程的按钮,我用它来显示我的系统正在处理。 使用thread1我打开一个jdialog并显示我的系统正在运行。我使用thread2关闭带有dlg.dispose()的jdialog 我的问题是,一旦我的程序停止运行,我再次单击按钮,然后出现一条错误消息,告诉我我的线程有问题 我有另一个按钮,后面没有线程,如果我再次单击它,它会完美地执行操作 谁能告诉我问题出在哪里吗?我尝试使用thread.currentThread().stop()关闭线程但它仍然不起作用 这是我的示例代码 pri
thread1
我打开一个jdialog并显示我的系统正在运行。我使用thread2
关闭带有dlg.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();
}
};
Thread.currentThread().stop();是否已弃用
试试下面的方法
Thread.currentThread().interrupt();
或
我的意见:
您正在UI线程上调用Thread.currentThread().stop()
删除这一行
thread2没有用,请删除它
通过SwingUtilities调用thread1.invokeLater(thread1)
您正在启动两个线程,无法确定哪个线程将首先运行。我现在不太记得Swing了,但如果首先处理对话框,然后调用setVisible(true)
会有什么好处,我会感到惊讶
您应该以.JDialog中解释的方式提供代码的确切错误消息是什么?我觉得这很像swing。若您正在运行调用组件上方法的线程,那个么它必须在UI线程上下文中运行。尝试通过SwingUtilities.invokeLater(Runnable)
或invokeAndWait(Runnable)
运行您的线程。我有在thread2中运行的代码,我只是没有将其复制到这里。如果我想保留thread2,并且我还想显示对话框,并在thread2完成运行后自动关闭它,有什么建议吗?或者有什么方法可以组合它呢?我会先启动thread2,然后调用join()
。如果它有一些与组件相关的操作,那么通过SwingUtilities.invokeAndWait()调用它。
private volatile boolean stopRequested = false;
public void run() {
while (!stopRequested) {
...
}
}
public void requestStop() {
stopRequested = true;
}