public interface Command {
public void execute() throws Exception;
}
public class ActiveObjectEngine {
LinkedList<Command> itscommands=new LinkedList<Command>();
public void addCommand(Command c) {
itsCommands.add(c);
}
public void run() {
whiel(!itsCommands.isEmpty()) {
Command c=(Command)itsCommands.getFirst();
itsCommands.removeFirst();
try {c.execute();}catch(Exception e) {}
}
}
}
public class SleepCommand implements Command {
private Command wakeupCommand=null;
private ActiveObjectEngine engine=null;
private long sleepTime=0;
private long startTime=0;
private boolean started=false;
public SleepCommand(long sleepTime,ActiveObjectEngine engine,command wakeupCommand) {
this.sleepTime=sleepTime;
this.engine=engine;
this.wakeupCommand=wakeupCommand;
}
public void execute() throws Exception {
long currentTime=System.currentTimeMillis();
if(!started) {
started=true;
startTime=currentTime;
engine.addCommand(this);
}else if((currentTime-startTime)<sleepTime)
engine.addCommand(this);
else
engine.addCommand(wakeupCommand);
}
}
public class DelayedTyper implements Command {
private long itsDelay;
private char itsChar;
private static ActiveObjectEngine engine=new ActiveObjectEngine();
private static boolean stop=false;
public static void main(String[] args) throws Exception {
engine.addCommand(new DelayedTyper(100,'1'));
engine.addCommand(new DelayedTyper(300,'3'));
engine.addCommand(new DelayedTyper(500,'5'));
engine.addCommand(new DelayedTyper(700,'7'));
Command stopCommand=new Command() {
public void execute() { stop=true; } };
engine.addCommand(new SleepCommand(5000,engine,stopCommand));
engine.run();
}
public DelayedTyper(long delay,char c) {
itsDelay=delay;
itsChar=c;
}
public void execute() throws Exception {
System.out.print(itsChar);
if(!stop)
delayAndRepeat();
}
private void delayAndRepeat() throws CloneNotSupportedException {
engine.addcommand(new SleepCommand(itsDelay,engine,this));
}
}