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

查看:31
本文介绍了如何在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.

我怎么能做这样的事情?

How can I do something like that?

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.

推荐答案

像某些人所说的那样尝试中断(),看看它是否对您的线程有任何影响.如果没有,请尝试销毁或关闭将使线程停止的资源.这有可能比尝试向其抛出 Thread.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天全站免登陆