I have a runnable object that is being updated every run (class variables). I want to be able to execute it in a single thread (presumeably SingleThreadExecutor?) BUT only after the previous run has completed.
I have tried Executors.newSingleThreadScheduledExecutor()
but it only offers time-based recurring tasks.
Also another problem I encountered that if I schedule the same runnable over and over (in a loop) it runs only once.
How can I acheive what I want?
The 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);
}
}
The launching part:
Population population = new Population();
ScheduledExecutorService ses = Executors
.newSingleThreadScheduledExecutor();
for (int i = 0; i < 300; i++)
ses.schedule(population, 0, TimeUnit.MILLISECONDS);
ses.shutdown();
You can simply run your code in a loop in a dedicated thread