我有一个可运行的对象,每次运行时都会更新(类变量)。我希望能够在单个线程中执行它(假设是SingleThreadExecutor?) BUT 只有在上一次运行完成后才能执行。
我尝试了Executors.newSingleThreadScheduledExecutor()
,但它只提供基于时间的重复性任务。
我遇到的另一个问题是,如果我反复安排相同的runnable(在循环中),它只运行一次。
我怎样才能实现我的目标?
班级:
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();
答案 0 :(得分:2)
您可以在专用线程的循环中运行代码
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++;
}
};