Runnable with a parameter?

uTubeFan picture uTubeFan · May 2, 2011 · Viewed 182.5k times · Source

I have a need for a "Runnable that accepts a parameter" although I know that such runnable doesn't really exist.

This may point to fundamental flaw in the design of my app and/or a mental block in my tired brain, so I am hoping to find here some advice on how to accomplish something like the following, without violating fundamental OO principles:

  private Runnable mOneShotTask = new Runnable(String str) {
    public void run(String str) {
       someFunc(str);
    }
  };  

Any idea how to accomplish something like the above?

Answer

corsiKa picture corsiKa · May 2, 2011

Well it's been almost 9 years since I originally posted this and to be honest, Java has made a couple improvements since then. I'll leave my original answer below, but there's no need for people to do what is in it. 9 years ago, during code review I would have questioned why they did it and maybe approved it, maybe not. With modern lambdas available, it's irresponsible to have such a highly voted answer recommending an antiquated approach (that, in all fairness, was dubious to begin with...) In modern Java, that code review would be immediately rejected, and this would be suggested:

void foo(final String str) {
    Thread t = new Thread(() -> someFunc(str));
    t.start();
}

As before, details like handling that thread in a meaningful way is left as an exercise to the reader. But to put it bluntly, if you're afraid of using lambdas, you should be even more afraid of multi-threaded systems.

Original answer, just because:

You can declare a class right in the method

void Foo(String str) {
    class OneShotTask implements Runnable {
        String str;
        OneShotTask(String s) { str = s; }
        public void run() {
            someFunc(str);
        }
    }
    Thread t = new Thread(new OneShotTask(str));
    t.start();
}