2

I have a question related to the following link: What's the difference between Thread start() and Runnable run()

In this question, I see a person creating runnable objects and then initializing them in two different ways. So, does this mean that you could pass these runnables around to other things at run time?

I want to pass code to a preexisting thread to be executed within that thread's loop. I was looking around and from what I can tell, you would want to create a dedicated runnable class like the following:

    public class codetobesent implements Runnable  
     {  
       public void run()  
        {   
        ..morecodehere.  
        }  
      ...insertcodestuffhere  
     }  

But how would I pass this to a thread that is already running? Say I'm trying to make a game and I have something special I want the renderer to do in its thread. How would I pass this runnable to that thread and have it run this data correctly?

My current implementation of my rendering thread is the following, I pulled it off of a tutorial site, and it has worked pretty well so far. But I want to know how to pass things to it so I can run more than what's just in the preset loop.

class RenderThread extends Thread 
{
private SurfaceHolder _curholder;
private UserView curview;
private boolean runrender = false; 

    public RenderThread (SurfaceHolder holder, UserView thisview)
    { //Constructor function - This gets called when you create a new instance of this object.
        curview = thisview;
        _curholder = holder;
    }

    public SurfaceHolder getThreadHolder()
    {
        return _curholder;
    }
    public void setRunning(boolean onoff) 
    {
        runrender = onoff;
    }
    @Override
    public void run() 
    {
        Canvas c;
        while (runrender)
        {
            c = null; //first clear the object buffer.
            try 
            {
              c = _curholder.lockCanvas(null); //lock the canvas so we can write to it
              synchronized (_curholder) 
              {//we sync the thread with the specified surfaceview via its surfaceholder.
                  curview.onDraw(c);
              }

            } 

            finally 
            {
              // do this in a finally so that if an exception is thrown
              // during the above, we don't leave the Surface in an
              // inconsistent state
                if (c != null) 
                {
                    _curholder.unlockCanvasAndPost(c);
                }
            }


        }

    }   



}
Community
  • 1
  • 1
Apothem Da Munster
  • 119
  • 1
  • 3
  • 11

1 Answers1

3

A Handler Thread implementation.

private void testWorker(){
        WorkerThread worker = new WorkerThread();
        worker.start();
        for (int i = 0; i < 10; i++) {
            worker.doRunnable(new Runnable() {
                public void run() {
                    Log.d("demo", "just demo");
                    try {
                        Thread.sleep(1000);//simulate long-duration operation.
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                };
            });
        }
    }

    private class WorkerThread extends HandlerThread implements Callback {

        private Handler mHandler;

        public WorkerThread() {
            super("Worker");
        }

        public void doRunnable(Runnable runnable) {
            if (mHandler == null) {
                mHandler = new Handler(getLooper(), this);
            }
            Message msg = mHandler.obtainMessage(0, runnable);
            mHandler.sendMessage(msg);
        }

        @Override
        public boolean handleMessage(Message msg) {
            Runnable runnable = (Runnable) msg.obj;
            runnable.run();
            return true;
        }

    }
Changwei Yao
  • 13,051
  • 3
  • 25
  • 22
  • So if I have multiple different kinds of runnables that are acting as an object property, I would just do the same thing from a reference list or something? As if I had an arraylist of runnables to be used? – Apothem Da Munster May 12 '12 at 00:56
  • It seems my question is also related to the following link as well: http://stackoverflow.com/questions/7462098/handlerthread-vs-executor-when-is-one-more-appropriate-over-the-other I Do want to do my processes one at a time for now, but I am still a little confused from the example in the above link about how to actually SEND the information to the handler. Or do you just do that with synchronize? – Apothem Da Munster May 12 '12 at 01:20
  • I post a handler thread demo. The runnable will be done one by one. – Changwei Yao May 12 '12 at 01:30
  • Dude, you rock. Thank you so much, that clears EVERYTHING up exceptionally well! I appreciate all your help and patience with this! – Apothem Da Munster May 12 '12 at 01:37
  • Handler thread runs on the UIThread, which shouldn't run anything than UI related stuff, to prevent laggy UI. – Kai May 12 '12 at 01:55
  • You can set a Main UI Thread Handler reference to the HandlerThread. and refresh the UI by sending a message back. – Changwei Yao May 12 '12 at 01:58
  • So do i make the WorkerThread inside of another class that extends Thread? – Apothem Da Munster May 12 '12 at 02:03
  • Okay, so by extending the handlerthread, it is acting as its own thread anyway. Please forgive me on all the extra questions, I'm still quite new to threading but I had one last thing I wanted to ask about this: So my question is now when you use mHandler.sendMessage(msg), you are sending the runnable to a messagequeue that mHandler has by creating it inside your HandlerThread object class? Is my guess correct or does mHandler.sendMessage send it somewhere else or do something different? – Apothem Da Munster May 12 '12 at 02:24
  • you are right. The handler Thread looper will take care of the messagequeue. – Changwei Yao May 12 '12 at 02:28