How to pause a Thread's Message Queue in Android?

﹥>﹥吖頭↗ 提交于 2019-12-23 02:32:05

问题


I am queuing up a bunch of runnables into a thread via a Handler.post(). I would like the ability to send a note to that thread that it should pause.

By pause I mean, finish the runnable or message you are currently working on, but don't go to the next message or runnable in your message queue until I tell you to continue.


回答1:


In case anyone else finds their way to this question, I ended up going with a ThreadPoolExecutor, using the example code in it's documentation for creating a PausableThreadPoolExecutor: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html

It doesn't use the Message Queue or Looper but it accomplishes what I was trying to do, which was to create a queue of Runnables that was able to be paused and/or canceled. It has the added bonus of being able to spread the queue over a specified number of threads.




回答2:


There is no pause method for Thread implemented in Java, but you can simulate a pause with a boolean, and waiting for the last message to finish is something you could do in your setter method of the boolean,

public void run(){
    while(!paused && !finised){
        // work
    }
}

public void setPause(boolean paused){
   //wait for your last message if there is one and then
    this.paused = paused;
}

and you should use an other boolean to know if the thread has finished, to exit the while.



来源:https://stackoverflow.com/questions/3886016/how-to-pause-a-threads-message-queue-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!