Showing posts with label Operating Systems. Show all posts
Showing posts with label Operating Systems. Show all posts

Thursday, 15 January 2015

CPU Scheduling algorithm - SJF (Java)


This is a Java program which implements one of the CPU Scheduling algorithm called Shortest Job First(SJF).

Shortest Job First algorithm reduces the waiting time  but it is impossible to implement  as the processor must know all the jobs/processes  in advance.

PROGRAM :
package codingcorner.in;

import java.util.Scanner;

public class SJF {
public static void main(String[] args) {
int i, j, temp, temp2, n;
float avgWt, totalWt = 0;
int a[] = new int[10];
Scanner scan = new Scanner(System.in);

System.out.print("Enter how many jobs ?\t");
n = scan.nextInt();
int bt[] = new int[100];
int wt[] = new int[100];

wt[1] = 0;
for (i = 1; i <= n; i++) {
System.out.print("Enter burst time for job " + i);
bt[i] = scan.nextInt();
a[i] = i; // stores job has how much burst time in array i
}
scan.close();
for (i = 1; i <= n; i++)
// ascending order of burst times and a[i]

for (j = i; j <= n; j++)

if (bt[i] > bt[j]) {
temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;
temp2 = a[i];
a[i] = a[j];
a[j] = temp2;
}

System.out.print("\nWaiting time for Job " + a[i] + " : 0 units \t");
for (i = 2; i <= n; i++) {
wt[i] = bt[i - 1] + wt[i - 1];
System.out.print("\nWaiting time for Job" + a[i] + ":\t" + wt[i]
+ " units \t");
totalWt = totalWt + wt[i];
}
System.out.print("\n\nThe total waiting time : " + totalWt);
avgWt = totalWt / n;
System.out.println("\n\nAverage waiting time : " + avgWt);
}
}

OUTPUT : 
Java - CPU Scheduling algorithm(SJF)



Wednesday, 14 January 2015

CPU Scheduling algorithm - FCFS (Java)


This is a Java program which implements one of the CPU Scheduling algorithm called First Come First Served(FCFS).

FCFS is the simplest scheduling algorithm , easy to understand and implement but not as efficient as remaining scheduling algorithms as its waiting time is high.

As the name suggests , here the processes/jobs are executed on first come first serve basis.

PROGRAM :
package codingcorner.in;

import java.util.Scanner;

public class FCFS {
public static void main(String[] args) {
int i,n;
float avgWt,totalWt=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many jobs ?\t");
n = scan.nextInt();
int bt[]= new int[n];
int wt[]= new int[n];
for(i=0;i<n;i++)
{
System.out.print("Enter burst time for job "+(i+1)+" :\t");
bt[i] = scan.nextInt();
}
scan.close();
System.out.print("\n\nWaiting time for Job 1 : 0 units\t");
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=bt[i-1]+wt[i-1];
System.out.print("\nWaiting time for Job"+(i+1)+" : "+wt[i]+" units \t");
totalWt = totalWt + wt[i];
}
System.out.print("\n\nThe total waiting time : "+totalWt);
avgWt= totalWt/n;
System.out.println("\n\nAverage waiting time : "+avgWt);
}
}
NOTE : Assuming that all jobs arrive at the same time.

OUTPUT : 
Java - CPU Scheduling Algorithm(FCFS)