0% found this document useful (0 votes)
29 views

Shortest Job First Java

The document shows an example of shortest job first (SJF) scheduling in Java. It defines a Process class with ID, arrival time, and burst time. It adds sample processes to a list, then performs SJF scheduling by adding processes to a priority queue ordered by burst time and tracking waiting time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Shortest Job First Java

The document shows an example of shortest job first (SJF) scheduling in Java. It defines a Process class with ID, arrival time, and burst time. It adds sample processes to a list, then performs SJF scheduling by adding processes to a priority queue ordered by burst time and tracking waiting time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;

class Process {

int id;

int arrivalTime;

int burstTime;

public Process(int id, int arrivalTime, int burstTime) {

this.id = id;

this.arrivalTime = arrivalTime;

this.burstTime = burstTime;

public class SJFScheduling {

public static void main(String[] args) {

List<Process> processes = new ArrayList<>();

processes.add(new Process(1, 0, 3));

processes.add(new Process(2, 1, 5));

processes.add(new Process(3, 2, 2));

processes.add(new Process(4, 3, 6));

sjfScheduling(processes);

public static void sjfScheduling(List<Process> processes) {

PriorityQueue<Process> queue = new PriorityQueue<>(Comparator.comparingInt(p ->


p.burstTime));

int currentTime = 0;
int totalWaitingTime = 0;

while (!processes.isEmpty() || !queue.isEmpty()) {

if (!processes.isEmpty() && processes.get(0).arrivalTime <= currentTime) {

queue.add(processes.remove(0));

continue;

if (queue.isEmpty()) {

currentTime = processes.get(0).arrivalTime;

continue;

Process currentProcess = queue.poll();

totalWaitingTime += currentTime - currentProcess.arrivalTime;

currentTime += currentProcess.burstTime;

System.out.println("Process " + currentProcess.id + " completed at time " + currentTime);

System.out.println("Average waiting time: " + (double) totalWaitingTime / (double) queue.size());

You might also like