gpt4 book ai didi

java - java中的循环任务

转载 作者:行者123 更新时间:2023-12-02 04:34:23 24 4
gpt4 key购买 nike

我有一个可运行的对象,每次运行都会更新(类变量)。我希望能够在单个线程(大概是 SingleThreadExecutor?)但是中执行它,只有在上一次运行完成之后。

我尝试过Executors.newSingleThreadScheduledExecutor(),但它只提供基于时间的重复任务。

我遇到的另一个问题是,如果我一遍又一遍地(在循环中)安排相同的可运行程序,它只会运行一次。

怎样才能达到我想要的效果?

类(class):

public class Population implements Runnable{
private int count=0;
...

@Override
public void run(){
evaluateAll();

List<Individual> parents = elitism();

individuals.clear();

for (int i = 0; i < popSize; i++) {
Individual child = Individual.uniformCrossover(parents);
if(Utilities.RANDOM.nextDouble() < mrate)
child.mutate();
individuals.add(child);
}

System.out.println(this);
}
}

启动部分:

Population population = new Population();
ScheduledExecutorService ses = Executors
.newSingleThreadScheduledExecutor();
for (int i = 0; i < 300; i++)
ses.schedule(population, 0, TimeUnit.MILLISECONDS);
ses.shutdown();

最佳答案

您可以简单地在专用线程中循环运行代码

public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
for (;;)
statefulRunnable.run();
});
}

public static final Runnable statefulRunnable = new Runnable() {
private int state;

@Override
public void run() {
state++;
}
};

关于java - java中的循环任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31015870/

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