views:

39

answers:

2

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.

A: 

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.

mklfarha
Thanks for a quick response. Is a Looper required for the thread to have a queue? If so how does that play into this picture?
littleFluffyKitty
To clarify that last question, where you have // work, what is happening there? If the thread is simply there to process runnables in the message queue, there isn't anything to put in the // work space. Where are the runnables that are posted to that thread running? Would that while statement actually effect them?
littleFluffyKitty
To only pause the thread i think so, and for the play you would call setPause(false); so it will go into the wile again, in the //work you would take out the next message or call the runnable that you need, think of it as an administrator of your queue...
mklfarha
Would you be able to give some example code? I'm still not quite sure how that would all look in regards to messages, handlers, etc. Thanks again.
littleFluffyKitty
A: 

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.

littleFluffyKitty