java 如何在android中杀死一个线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16653820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:34:50  来源:igfitidea点击:

How to kill a thread in android?

javaandroidmultithreading

提问by Mr.Noob

I've got a background thread running in my application and I need to kill it safely. How can I kill a thread in java other than using a boolean flag? I have read that i cannot use thread.stop() anymore as it is not safe. but is there a proper way of doing this? can someone give me a code snippet for it please?

我的应用程序中有一个后台线程正在运行,我需要安全地终止它。除了使用布尔标志之外,如何在 Java 中杀死线程?我读过我不能再使用 thread.stop() 因为它不安全。但是有没有正确的方法来做到这一点?有人可以给我一个代码片段吗?

Thanks

谢谢

回答by Gabe Sechan

Its never safe in any language to kill a thread- you don't know what that thread may be doing and what state it may leave behind. Using the cancel method with the thread occassionally checking isCanceled allows the thread to manage its own safety- it can choose to do this only when it would be safe to kill itself or to do the needed cleanup.

杀死线程在任何语言中都永远不会安全 - 您不知道该线程可能在做什么以及它可能留下什么状态。使用带有线程的取消方法偶尔检查 isCanceled 允许线程管理自己的安全 - 只有当它可以安全地杀死自己或进行所需的清理时,它才能选择这样做。

If you don't actually need to kill a thread but just want to wait until its over, use join.

如果您实际上不需要杀死一个线程而只想等到它结束,请使用 join。

If you absolutely need to kill a thread, go ahead and use stop. Just don't expect your state to be safe or consistent afterwards- this should really only be done when terminating the application/activity.

如果您绝对需要终止线程,请继续使用 stop。只是不要期望您的状态在之后是安全的或一致的 - 这实际上应该只在终止应用程序/活动时完成。

回答by chuckliddell0

Try using something like

尝试使用类似的东西

service.getThread().interrupt();
service.setThread(null);

Or

或者

thread.interrupt();
thread = null;

回答by quangnhat008

You need using flag. For ex:

您需要使用标志。例如:

private boolean isThOn; //flag isThOn
long delaytime;
int times;
...
new Thread() {
        public void run() {
            int i=0;
            isThOn = true;
            while (isThOn && i<times) {
                try {
                    i++;
                    //{...}
                    if (i == times) isThOn = false;
                    sleep(delaytime);
                } catch (Exception e) {e.printStackTrace();}
            }
        }
}.start();
public void cancelthd() {
    isThOn = false; //whileloop will stop if isThOn = false -> Thread will Terminated befor i = times.
}