我收到这个错误 -
不能访问类型为GeoLocation的封闭实例.必须使用GeoLocation类型的封闭实例限定分配(egxnew A(),其中x是GeoLocation的实例).这个错误出现在新的ThreadTask(i)上.我不知道为什么会这样.任何建议将不胜感激.
public class GeoLocation {
public static void main(String[] args) throws InterruptedException {
int size = 10;
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
for(int i = 0; i < 3 * size; i++) {
service.submit(new ThreadTask(i));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
class ThreadTask implements Runnable {
private int id;
public ThreadTask(int id) {
this.id = id;
}
public void run() {
System.out.println("I am task " + id);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 149
嗨,我找到了解决方案;-)
发生此错误是因为您尝试创建内部类的实例service.submit(new ThreadTask(i));
而不创建主类的实例.
要解决此问题,请首先创建主类的实例:
GeoLocation outer = new GeoLocation();
Run Code Online (Sandbox Code Playgroud)
然后创建要调用的类的实例,如下所示:
service.submit(outer.new ThreadTask(i));
Run Code Online (Sandbox Code Playgroud)
我希望这能解决你的问题;-)
Dan*_*anO 98
另一个选项,也就是我喜欢的选项,是将内部类设置为静态.
public static class ThreadTask implements Runnable { ... }
Run Code Online (Sandbox Code Playgroud)
kan*_*ear 15
制作内联类 static
.
public class OuterClass {
static class InnerClass {
}
public InnerClass instance = new OuterClass.InnerClass();
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以按如下方式实例化内部类:
new OuterClass.InnerClass();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
89611 次 |
最近记录: |