Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass parameters to a Runnable? [duplicate]

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.

like image 630
Yevgeny Simkin Avatar asked Feb 03 '12 03:02

Yevgeny Simkin


People also ask

Is there a way to pass parameters to a runnable interface?

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.

Can we pass a parameter to run of a thread?

No you can't pass parameters to the run() method.

Can runnable return a value?

The run method of Runnable has return type void and cannot return a value.


2 Answers

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); 
like image 80
Lalit Poptani Avatar answered Sep 29 '22 03:09

Lalit Poptani


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     } } 
like image 25
Romain Guy Avatar answered Sep 29 '22 02:09

Romain Guy