0

So I have the following thread:

  public class MyThread extends Thread
{
  Handler cHandler;
 private boolean looprunning = false;
  MyThread() {
  cHandler = new Handler();
          looprunning = true;

  }

  @Override
  public void run(){
      while (looprunning) {
          //do stuff here
        //update another system here or something else.
      }
  }

}

Inside the while loop of this thread, I want to run a Runnable that I pass to the thread while the thread is looping inside that while loop. How do I do this?

Apothem Da Munster
  • 119
  • 1
  • 3
  • 11

2 Answers2

2

first please mark looprunning as volatile for proper thread visibility

you can use a queue

Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();
@Override
public void run(){
   while (looprunning) {
       //do stuff here
     //update another system here or something else.
     Runnable r = taskQueue.poll();
     if(r!=null)r.run();
   }
} 

you can use a (thread-safe) queue of your choice

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • wait that's it? You mean to tell me that I don't need to use a handler to post messages to the thread? I can just send the runnable to this list, the one of which I'm assuming you're using is thread-safe, instead of something with a looper or doing handler.sendmessage() – Apothem Da Munster May 16 '12 at 14:00
1

Android already provides a mechanism for creating threads that run in loops that execute Runnables. Have a look at HandlerThread

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Is there a way to make that handlerthread actually have a loop of logic constantly going? Like in my example? I tried HandlerThread and from what I can tell, you dont want to override run(), but it processes messages one at a time. So I send a loop like in the example, the handler thread locks. – Apothem Da Munster May 16 '12 at 13:23
  • 1
    Sorry, I guess I misunderstood what you are trying to do. I didn;t realize that you wanted to have the thread looping constantly doing something else and then have it **additionally** run some Runnable that you send to it while it loops. In that case, the suggestion from @ratchetfreak seems reasonable. – David Wasser May 16 '12 at 13:55
  • Thank you very much for the verification on that. I made the same mistake myself when I first started trying to figure out how to do this. Hilariously enough, that was the same answer I got on my last question, and I thought that was it. http://stackoverflow.com/questions/10560166/pass-a-runnable-to-a-pre-existing-thread-to-be-run-in-android-java – Apothem Da Munster May 16 '12 at 14:05