Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Parameterized Runnable

Standard Runnable interface has only non-parametrized run() method. There is also Callable<V> interface with call() method returning result of generic type. I need to pass generic parameter, something like this:

interface MyRunnable<E> {
  public abstract void run(E reference);
}
Is there any standard interface for this purpose or I must declare that basic one by myself?
like image 414
mschayna Avatar asked Nov 02 '09 08:11

mschayna


People also ask

Can we pass parameter to run method in Java?

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

What is callable and runnable in Java?

Callable interface and Runnable interface are used to encapsulate tasks supposed to be executed by another thread. However, Runnable instances can be run by Thread class as well as ExecutorService but Callable instances can only be executed via ExecutorService.


1 Answers

Typically you would implement Runnable or Callable with a class that supports a generic input parameter; e.g.

public class MyRunnable<T> implements Runnable {
  private final T t;

  public MyRunnable(T t) {
    this.t = t;
  }

  public void run() {
    // Reference t.
  }
}
like image 89
Adamski Avatar answered Oct 07 '22 08:10

Adamski