Is there a way to pass parameters to a Runnable?

Yevgeny Simkin picture Yevgeny Simkin · Feb 3, 2012 · Viewed 72.3k times · Source

I have a thread that uses a handler to post a runnable instance. it works nicely but I'm curious as to how I would pass params in to be used in the Runnable instance? Maybe I'm just not understanding how this feature works.

To pre-empt a "why do you need this" question, I have a threaded animation that has to call back out to the UI thread to tell it what to actually draw.

Answer

Lalit Poptani picture Lalit Poptani · Feb 3, 2012

Simply a class that implements Runnable with constructor that accepts the parameter can do,

public class MyRunnable implements Runnable {
  private Data data;
  public MyRunnable(Data _data) {
    this.data = _data;
  }

  @override
  public void run() {
    ...
  }
}

You can just create an instance of the Runnable class with parameterized constructor.

MyRunnable obj = new MyRunnable(data);
handler.post(obj);