Java program for Safe Sequence (Banker's Algorithm).

//Java program for safe sequence of Banker's algorithm.

import java.util.*;
class SafeAlgo
{
 public static void main(String args[])
 {
  Scanner sc=new Scanner(System.in);
  System.out.println("Enter number of processes:");
  int n=sc.nextInt();
  int p[]=new int[n];
  int flag[]=new int[n];
  System.out.println("Enter number of resource variables");
  int m=sc.nextInt();
  
  int max[][]=new int[n][m];
  int allo[][]=new int[n][m];
  int need[][]=new int[n][m];
  int avail[]=new int[m];
  for(int x=0;x<n;x++)
  {
   System.out.println("Enter process number:");
   p[x]=sc.nextInt();
   flag[x]=0;
   for(int y=0;y<m;y++)
   {
    System.out.println("Max -> P"+p[x]+" ->"+y+" :");
    max[x][y]=sc.nextInt();    
    
   }
   for(int y=0;y<m;y++)
   {
    System.out.println("Allocation -> P"+p[x]+" ->"+y+" :");
    allo[x][y]=sc.nextInt();
    need[x][y]=max[x][y]-allo[x][y];
   }
  }
  System.out.println("Enter available resources:");
  for(int y=0;y<m;y++)
   avail[y]=sc.nextInt();
  
  System.out.println("Process\tMax\tAllocation\tNeed");
  for(int x=0;x<n;x++)
  {
   System.out.print("P"+p[x]+"\t");
   for(int y=0;y<m;y++)
    System.out.print(max[x][y]+" ");
   System.out.print("\t");
   for(int y=0;y<m;y++)
    System.out.print(allo[x][y]+" ");
   System.out.print("\t\t");
   for(int y=0;y<m;y++)
    System.out.print(need[x][y]+" ");
   System.out.println();
  }
  
  int count=0;
  while(count<=n)
  {
   
    for(int x=0;x<n;x++)
    {
     if(flag[x]==0)
     {
     int f=0;
     for(int y=0;y<m;y++)
     {      
      if(avail[y]<need[x][y])
      {
       f=1;
       break;
      }
     }
       
     if(f==0)
     {
      flag[x]=1;
      for(int y=0;y<m;y++)
      {
       avail[y]+=allo[x][y];
      }
      System.out.println("P"+p[x]);
      count++;
     }
     }
    }
   }
  }
 }

Comments

Popular posts from this blog

Priority Scheduling Algorithm Java Program.

Implement UNIX system calls like ps, fork, join, exec family, and wait for process management (use shell script/ Java/ C programming).

Implement a class CppArray which is identical to a one-dimensional C++ array (i.e., the index set is a set of consecutive integers starting at 0) except for the following : 1. It performs range checking. 2.It allows one to be assigned to another array through the use of assignment operator. 3.It supports a function that returns the size of the array.