开发者

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

I am q开发者_如何转开发ueuing 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜