You can take a look at this code that handles timing:
import java.util.*;
volatile int state=-1;
//Intervals in millis
long timings[]={2000, 3000, 5000};
//timer class used
Timer timers[]=new Timer[timings.length];
//A creates the timer task that switches to state i
TimerTask createTask(final int i) {
return new TimerTask() {
@Override void run() {
//If you want additional code to be executed when the state gets switched to i do it here.
state=i;
}
};
}
void setup() {
//Creates the timers and sets them to be executed at the givens intervals.
for (int i=0; i<timings.length; i++) {
timers[i]=new Timer();
timers[i].scheduleAtFixedRate(createTask(i),
/*Time until first execution*/ timings[i],
/*Interval in wich execution is done*/ timings[i]);
}
}
void draw() {
println(state);
}
Also an option you might explore would be looking into the registerMethod method. Here would be a little example on one possible application:
public abstract class Task {
public abstract void draw();
}
public class TaskA extends Task{
public void draw() {
println("Hi");
}
}
public class TaskB extends Task{
public void draw() {
println("Hello");
}
}
Task ta=new TaskA();
Task tb=new TaskB();
void setup() {
//The draw method of the Object ta is executed after the draw method of this sketch
this.registerMethod("draw",ta);
}
//Any method where you do not want two threads executing the method at the same time should be declared synchronized
synchronized void swap(Task t1,Task t2){
this.unregisterMethod("draw",t1);
this.registerMethod("draw",t2);
}
void draw(){
if(frameCount==300) swap(ta,tb);
}
I hope these examples help you!