HandlerThread VS执行人 - 当一个比较合适的比其他? [英] HandlerThread vs Executor - When is one more appropriate over the other?

查看:273
本文介绍了HandlerThread VS执行人 - 当一个比较合适的比其他?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是好奇,是否有次,我应该选择执行程序通过 HandlerThread 。是否有时间,一个是优于其他的,还是应该我真的只是坚持与 HandlerThread ?就我而言,我目前正在听的ServerSocket 的连接,和处理由一个执行程序创建一个单独的线程每个请求。虽然我给一个具体的例子,我真的只是为了寻找案件,其中一个比另一个更合适。不过,我欢迎评论我的设计。

I'm just curious about whether there are times in which I should choose an Executor over a HandlerThread. Are there times that one is superior over the other, or should I really just stick with the HandlerThread? In my case, I'm currently listening to a ServerSocket for connections, and handling each request on a separate thread created by an Executor. Even though I gave a specific example, I'm really just looking for cases in which one is more appropriate than the other. However, I welcome comments about my design.

推荐答案

执行人类是功能更强大,可以使用一个线程池,而每一个处理程序引用一个线程。执行人可以让你把所有的计划任务,并取消他们,如果你愿意的话。在另一方面,处理器不会回答简单的问题,例如,有多少任务在等待或者给我提述所有等待任务。我认为原因之一是,处理程序较为有限,因为Android的,您可以访问它使用的用户界面的主要处理程序,你可能真的搞砸了操作系统,如果你开始取消OS的任务。

The Executor class is more powerful and can use a pool of threads, whereas each Handler references a single thread. The Executor allows you to get all the scheduled tasks and cancel them if you'd like. The Handler on the other hand will not answer simple questions such as, how many tasks are waiting or give me a reference to all waiting tasks. I believe one reason that the Handler is more limited is because Android gives you access to the main Handler it uses for the UI and you could really screw up the OS if you started canceling OS tasks.

在一般的,如果你需要的线程或者大量的权力使用的执行者池。如果你只需要一个很好的后台线程同时运行一个任务使用一个处理程序。正如当我想查询我的数据库一个​​例子,我只是真的想一个查询发生在同一时间,我不希望产生ANR所以我用在后台线程运行的处理器来运行我的查询。

In general if you need a pool of threads or lots of power use the Executor. If you just need a nice background thread to run one task at a time use a Handler. As an example when I want to query my database I only really want one query to occur at a time and I don't want to generate an ANR so I use a Handler running on a background thread to run my queries.

我相信,因为你要同时处理多个传入的请求和处理程序只能做一次你选择执行人的声音为宜。

I believe your choice of executor sounds appropriate since you want to handle multiple incoming requests simultaneously and a Handler can only do one at a time.

更新:如何创建一个后台线程运行的处理程序:

在您的构造函数或写的onCreate下,很明显,你可以设置任何你喜欢的优先级:

In your constructor or onCreate write the following, obviously you can set the priority to whatever you like:

public class MyClass {

    private Handler mBgHandler;

    public MyClass() {
        HandlerThread bgThread = new HandlerThread("My-Background-Handler");
        bgThread.start();
        mBgHandler = new Handler(bgThread.getLooper());
    }
}

更新:不要忘了退出()或quitSafely()你HandlerThread当你用它完成,否则将继续等下去

这篇关于HandlerThread VS执行人 - 当一个比较合适的比其他?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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