Write a scheduler in java which lists the tasks in the priority order based on the priority of the task and the duration it takes to complete.
import java.util.PriorityQueue;
public class TaskScheduler {
public static void main(String[] args) {
// Create a priority queue to store tasks
PriorityQueue<Task> taskQueue = new PriorityQueue<>();
// Add tasks to the priority queue
taskQueue.add(new Task("Task 1", 2, 15));
taskQueue.add(new Task("Task 2", 1, 10));
taskQueue.add(new Task("Task 3", 2, 20));
// Process tasks in order of priority
while (!taskQueue.isEmpty()) {
Task task = taskQueue.poll();
System.out.println("Processing task: " + task.getName());
}
}
}
class Task implements Comparable<Task> {
private String name;
private int priority;
private int duration;
public Task(String name, int priority, int duration) {
this.name = name;
this.priority = priority;
this.duration = duration;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
public int getDuration() {
return duration;
}
@Override
public int compareTo(Task other) {
int priorityComparison = Integer.compare(this.priority, other.priority);
if (priorityComparison != 0) {
return priorityComparison;
} else {
return Integer.compare(this.duration, other.duration);
}
}
}