HandlerThread vs Executor - When is one more appropriate over the other?

后端 未结 2 1909
心在旅途
心在旅途 2020-12-07 12:44

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 ove

2条回答
  •  隐瞒了意图╮
    2020-12-07 13:23

    I wouldn't follow the sample code in satur9nine's answer as of 2011-Dec-22.

    Thread.MIN_PRIOROTY is mapped to android.os.Process.THREAD_PRIORITY_LOWEST. Quote:

    Lowest available thread priority. Only for those who really, really don't want to run if anything else is happening.

    I would at least use android.os.Process.THREAD_PRIORITY_BACKGROUND, like so:

    HandlerThread bgThread = new HandlerThread("handler name");
    Process.setThreadPriority(bgThread.getThreadId(), Process.THREAD_PRIORITY_BACKGROUND);
    bgThread.start();
    mBgHandler = new Handler(bgThread.getLooper());
    

    This assigns the default Android background priority to the thread.

    Currently, threads of priority Process.THREAD_PRIORITY_BACKGROUND and lower share an artificially limited amount of CPU time by means of a Linux cgroup, see for example here. If a background task does not just wait for I/O but performs real computations, I'd consider increasing its priority by android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE which (currently) moves it out of the background cgroup while still not substantially endangering UI and real time activities.

    Update: satur9nine's answer was silently revised on 2013-Jan-08 to not set the lowest possible priority any more. The HandlerThread will now implicitly have a priority of android.os.Process.THREAD_PRIORITY_BACKGROUND. This means that it now gets the default background task priority but it is still limited to consume an artificial maximum of 10% CPU time along with all another background tasks which may exist. If that's not desired, use my code above e.g. with

    Process.setThreadPriority(bgThread.getThreadId(),
                              Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
    

    to lift your background thread out of the cgroup.

提交回复
热议问题