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

非 Y 不嫁゛ 提交于 2019-11-28 20:53:19

问题


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.


回答1:


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);



回答2:


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
    }
}



回答3:


If you need to communicate information into a Runnable, you can always have the Runnable object constructor take this information in, or could have other methods on the Runnable that allow it to gain this information, or (if the Runnable is an anonymous inner class) could declare the appropriate values final so that the Runnable can access them.

Hope this helps!




回答4:


Although you can use any of the above the answer, but if you question is really concerned about android then you can also use AsyncTask.




回答5:


I think a found a simpler approach:

public interface MyRunnable extends Runnable {
    public void run(int data);
}

public void someMethod(int n, String s, MyRunnable r) {
   ...
   r.run(n);
   ...
}

the call:

someMethod(5, "Hello", new MyRunnable() {

    @Override
    public void run(int data) {
        // TODO Auto-generated method stub

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
});


来源:https://stackoverflow.com/questions/9123272/is-there-a-way-to-pass-parameters-to-a-runnable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!