Interview Question
Software EngineersCountry: United States
public class Task {
private Runnable runnable;
private int seconds;
public Runnable getRunnable() {
return runnable;
}
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
public class MyTimer extends System{
Queue<Task> queue = new LinkedList<Task>();
Boolean flag;
@Override
public void schedule(Runnable runnable, int seconds) {
if(!queue.isEmpty()){
Task task = queue.remove();
if(flag){
super.schedule(task.getRunnable(), task.getSeconds());
}
flag = true;
} else{
super.schedule(runnable, seconds);
}
Task newTask = new Task();
newTask.setRunnable(runnable);
newTask.setSeconds(seconds);
queue.add(newTask);
}
}
A more simple solution is given below:
public class Task {
private Runnable runnable;
private int seconds;
public Runnable getRunnable() {
return runnable;
}
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
public class MyTimer extends System{
Queue<Task> queue = new LinkedList<Task>();
@Override
public void schedule(Runnable runnable, int seconds) {
Task newTask = new Task();
newTask.setRunnable(runnable);
newTask.setSeconds(seconds);
queue.add(newTask);
Task task = queue.remove();
super.schedule(task.getRunnable(), task.getSeconds());
}
}
We can maintain a queue of tasks inside the MyTimer class, and do the following whenever mySchedule(runnable,int ) is called:
- Kumar April 16, 20151.if queue is empty, push the new task in the queue, and call system.schedule() on task at head of the queue.
2.if queue is not empty push the task.
3.When the call to system.schedule() completes, dequeue task from taskqueue and call schedule on it.