So I have this code here, that adds my “NamePrinter” runnable class as ExecutorService tasks. Everything works fine, but I’d like to get rid of that extra class. So I am asking is there a way to submit method to ExexutorService?
Here is the code that I currently have:
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();
}
But I’d like it to be something like this:
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);
}
Is this something that is possible to achieve?
The closest you can come as an anonymous inner class: