[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();
}
});
Java Thread run() method The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.
As a quick reminder, we can create a thread in Java by implementing Runnable or Callable. To run a thread, we can invoke Thread#start (by passing an instance of Runnable) or use a thread pool by submitting it to an ExecutorService.
Since you added a type parameter <T>
to your constructor, it shadows the type parameter for the class. Therefore, the T
for the constructor argument pMethod
is a different T
than the class parameter, which is what Eclipse is warning you about. Just change the signature for the constructor to public MyExecutor(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With