问题描述
我想知道哪种方法是停止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 Thread
s 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-停止线程的最佳安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!