gpt4 book ai didi

java - 将方法提交到 ExecutorService Java

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:59:13 26 4
gpt4 key购买 nike

所以我这里有这段代码,它将我的“NamePrinter”可运行类添加为 ExecutorService 任务。一切正常,但我想摆脱那个额外的类(class)。所以我问有没有办法向 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);

}

这是有可能实现的吗?

最佳答案

最接近的匿名内部类:

for (int i = 0; i < 10; i++) {
final int x = i;
futures.add(es.submit(new Runnable() {
@Override public void run() {
namePrint(x + "name");
}
}));
}

关于java - 将方法提交到 ExecutorService Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11632896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com