Android-停止线程的最佳安全方法 [英] Android - Best and safe way to stop thread

查看:99
本文介绍了Android-停止线程的最佳安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪种方法是停止Android中线程的最佳方法.我知道我可以使用AsyncTask代替它,并且有一个cancel()方法.在我的情况下,我必须使用Thread.这是我使用Thread的方式:

I want to know which is the best way to stop a thread in Android. I know I can use AsyncTask instead of it and that there is a cancel() method. I have to use Threads in my situation. Here is how I'm using Thread:

Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //doing some work
        }
    };
new Thread(runnable).start();

那么,有谁知道停止线程的最佳方法是什么?

So, does anyone have any idea of which is the best way to stop a thread?

推荐答案

您应该使线程支持中断.基本上,您可以调用yourThread.interrupt()来停止线程,并且需要在run()方法中定期检查Thread.interrupted()

You should make your thread support interrupts. Basically, you can call yourThread.interrupt() to stop the thread and, in your run() method you'd need to periodically check the status of Thread.interrupted()

此处.

这篇关于Android-停止线程的最佳安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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