-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreemptiveSJf.java
More file actions
90 lines (72 loc) · 3.37 KB
/
PreemptiveSJf.java
File metadata and controls
90 lines (72 loc) · 3.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.*;
class Process {
int pid, arrivalTime, burstTime, remainingTime, completionTime, waitingTime, turnaroundTime;
Process next;
public Process(int pid, int arrivalTime, int burstTime) {
this.pid = pid;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
this.remainingTime = burstTime;
this.next = null;
}
}
class SJFPreemptive {
List<Process> processList = new ArrayList<>();
public void addProcess(int pid, int arrivalTime, int burstTime) {
processList.add(new Process(pid, arrivalTime, burstTime));
}
public void executeProcesses() {
int currentTime = 0, completed = 0;
int n = processList.size();
double totalWaitingTime = 0, totalTurnaroundTime = 0;
Process executingProcess = null;
while (completed < n) {
Process shortest = null;
for (Process p : processList) {
if (p.arrivalTime <= currentTime && p.remainingTime > 0) {
if (shortest == null || p.remainingTime < shortest.remainingTime) {
shortest = p;
}
}
}
if (shortest == null) {
currentTime++; // No process available, increment time
continue;
}
shortest.remainingTime--;
if (shortest.remainingTime == 0) {
completed++;
shortest.completionTime = currentTime + 1;
shortest.turnaroundTime = shortest.completionTime - shortest.arrivalTime;
shortest.waitingTime = shortest.turnaroundTime - shortest.burstTime;
totalWaitingTime += shortest.waitingTime;
totalTurnaroundTime += shortest.turnaroundTime;
}
currentTime++;
}
// Print results
System.out.println("\nProcess ID Arrival Time Burst Time Waiting Time Turnaround Time");
for (Process p : processList) {
System.out.printf("%-11d %-13d %-10d %-12d %d%n", p.pid, p.arrivalTime, p.burstTime, p.waitingTime, p.turnaroundTime);
}
System.out.printf("Avg. waiting time = %.6f%n", totalWaitingTime / n);
System.out.printf("Avg. turnaround time = %.6f%n", totalTurnaroundTime / n);
}
}
public class PreemptiveSJf {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SJFPreemptive scheduler = new SJFPreemptive();
System.out.print("Enter the number of processes: ");
int n = sc.nextInt();
System.out.println("Enter process ID, arrival time, and burst time for each process:");
for (int i = 0; i < n; i++) {
int pid = sc.nextInt();
int arrivalTime = sc.nextInt();
int burstTime = sc.nextInt();
scheduler.addProcess(pid, arrivalTime, burstTime);
}
scheduler.executeProcesses();
sc.close();
}
}