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.
The first way we can send a parameter to a thread is simply providing it to our Runnable or Callable in their constructor. Note that the reason this works is that we've handed our class its state before launching the thread.
No you can't pass parameters to the run() method.
The run method of Runnable has return type void and cannot return a value.
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);
There are various ways to do it but the easiest is the following:
final int param1 = value1; final int param2 = value2; ... new Runnable() { public void run() { // use param1 and param2 here } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With