如何在java中快速,干净地中止线程? [英] How to abort a thread in a fast and clean way in java?

查看:121
本文介绍了如何在java中快速,干净地中止线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:我有一个对话框,其中包含一些用户可以更改的参数(例如通过微调器)。每次更改其中一个参数时,我都会根据新参数值启动一个线程来更新3D视图。
如果用户在第一个线程正在工作时更改另一个值(或者通过在微调器箭头上多次单击再次使用相同的值),我想中止第一个线程(以及更新3D视图)和使用最新的参数值启动一个新的。

Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value. If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.

我该怎样做?

PS:我的线程的 run()方法中没有循环,因此检查标志不是一个选项:更新3D视图的线程基本上只调用一个方法执行起来很长。我无法在此方法中添加任何标志,要求中止,因为我无法访问其代码。

PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.

推荐答案

尝试中断()正如一些人所说,看看它是否对你的线程有任何影响。如果没有,请尝试销毁或关闭将使线程停止的资源。这有可能比尝试抛出Th​​read.stop()更好一点。

Try interrupt() as some have said to see if it makes any difference to your thread. If not, try destroying or closing a resource that will make the thread stop. That has a chance of being a little better than trying to throw Thread.stop() at it.

如果性能可以忍受,您可以将每个3D更新视为离散不可中断的事件,让它一直运行到结束,然后检查是否有新的最新更新要执行。这可能会使GUI对用户有点不稳定,因为他们可以进行五次更改,然后查看事物前五次更改的图形结果,然后查看最新更改的结果。但是根据这个过程的持续时间,它可能是可以容忍的,并且它可以避免必须杀死线程。设计可能如下所示:

If performance is tolerable, you might view each 3D update as a discrete non-interruptible event and just let it run through to conclusion, checking afterward if there's a new latest update to perform. This might make the GUI a little choppy to users, as they would be able to make five changes, then see the graphical results from how things were five changes ago, then see the result of their latest change. But depending on how long this process is, it might be tolerable, and it would avoid having to kill the thread. Design might look like this:

boolean stopFlag = false;
Object[] latestArgs = null;

public void run() {
  while (!stopFlag) {
    if (latestArgs != null) {
      Object[] args = latestArgs;
      latestArgs = null;
      perform3dUpdate(args);
    } else {
      Thread.sleep(500);
    }
  }
}

public void endThread() {
  stopFlag = true;
}

public void updateSettings(Object[] args) {
  latestArgs = args;
}

这篇关于如何在java中快速,干净地中止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆