作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
[检查问题底部的更新]
如标题所示,我想编写一个接受方法并在新线程中执行该方法的类。我潜伏在 SO 周围并想出了类似的东西:
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();
}
}
}
但是 Eclipse 警告我,在构造函数中,在
this.method = pMethod;
我cannot convert from Callable <T> to Callable <T>
.
我好像做错了什么,但我无法理解。
更新
原来我是在重新发明轮子,我想做的可以这样实现:
public class MyExecutor implements Executor{
@Override
public void execute(Runnable command) {
new Thread(command).start();
}
}
在主流程中,一个方法可以像这样在一个新线程中执行:
MyExecutor myExec = new MyExecutor();
myExec.execute(new Runnable() {
@Override
public void run() {
myMethod();
}
});
最佳答案
因为你添加了一个类型参数 <T>
对于您的构造函数,它隐藏了类的类型参数。因此,T
对于构造函数参数 pMethod
是不同的T
而不是类参数,这是 Eclipse 警告您的内容。只需将构造函数的签名更改为 public MyExecutor(...)
.
关于Java - 将方法传递给类并在新线程中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38848732/
我是一名优秀的程序员,十分优秀!