[Check the bottom of the question for updates]
As in the title, I'd like to write a class which takes in a method and executes it in a new Thread. I lurked around SO and came up with something like:
import java.util.concurrent.Callable;
public class MyExecutor<T> implements Runnable{
private Callable<T> method;
public <T> MyExecutor(Callable<T> pMethod){
this.method = pMethod;
}
@Override
public void run() {
try {
// start a new Thread, then
method.call();
} catch (Exception e) {
System.err.println("Failed calling method "+method.getClass());
e.printStackTrace();
}
}
}
However Eclipse warns me that, inside the constructor, in
this.method = pMethod;
I cannot convert from Callable <T> to Callable <T>
.
It smells like I'm doing something entirely wrong, but I can't grasp it.
UPDATE
Turns out I was reinventing the wheel, what I wanted to do can be attained like this:
public class MyExecutor implements Executor{
@Override
public void execute(Runnable command) {
new Thread(command).start();
}
}
In the main flow a method can be executed in a new thread like this:
MyExecutor myExec = new MyExecutor();
myExec.execute(new Runnable() {
@Override
public void run() {
myMethod();
}
});
<T>
before your constructor is declaring a second generic type, also calledT
. If you remove it, your code should be ok. – Historiographer