所以我在这里有这段代码,它将我的“NamePrinter”可运行类添加为 ExecutorService 任务。一切正常,但我想摆脱那个额外的课程。所以我问有没有办法向 ExexutorService 提交方法?
这是我目前拥有的代码:
public void start(){
Collection<Future<?>> futures = new LinkedList<>();
final ExecutorService es = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < 10; i++) {
futures.add(es.submit(new NamePrinter(name)));
}
es.shutdown();
}
但我希望它是这样的:
public void start(){
Collection<Future<?>> futures = new LinkedList<>();
final ExecutorService es = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < 10; i++) {
futures.add(es.submit(namePrint(i+"name"))); // This code doesn't work, I just made it so you could understand what I mean.
}
es.shutdown();
}
public void namePrint(String name){ // I'd like this to be the task that ExecutorService runs.
System.out.println(name);
}
这是可以实现的吗?