Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- class BullyAlgorithm
- {
- boolean process[];
- int coordinator,n;
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- void ip()
- {
- System.out.print("Enter number of Processes ");
- try
- {
- n=Integer.parseInt(br.readLine());
- process=new boolean[n];
- for(int i=0;i<n;i++)
- process[i]=true;
- }
- catch(IOException ie)
- {
- System.out.println("Error");
- }
- coordinator=n;
- }
- void election()
- {
- int comm=0,max=0;
- try
- {
- comm=Integer.parseInt(br.readLine());
- if(!process[comm-1])
- System.out.println("Dead Process");
- else
- {
- for(int i=comm;i<=n;i++)
- System.out.println("Request Message to Process "+i);
- for(int i=comm;i<=n;i++)
- {
- if(process[i-1])
- {
- ` if(max<i)
- max=i;
- System.out.println("Reply Message to Process "+i);
- }
- }
- System.out.println("The Co-ordinator is "+max);
- coordinator=max;
- }
- }
- catch(IOException ie)
- {
- System.out.println("Error");
- }
- }
- void menu()
- {
- int choice=0,id=0;
- do
- {
- System.out.println("Enter");
- System.out.println("1. Crash");
- System.out.println("2. Recover");
- System.out.println("3. Check Coordinator");
- System.out.println("4. Increase Number of Processes");
- System.out.println("0. Exit");
- try
- {
- choice=Integer.parseInt(br.readLine());
- }
- catch(IOException ie)
- {
- System.out.println("Error");
- }
- switch(choice)
- {
- case 1:
- {
- try
- {
- id=Integer.parseInt(br.readLine());
- }
- catch(IOException ie)
- {
- System.out.println("Error");
- }
- if(process[id-1])
- {
- process[id-1]=false;
- System.out.println("Process Crashed ");
- if(id==coordinator)
- election();
- }
- else
- {
- System.out.println("Process Already Dead");
- }
- break;
- }
- case 2:
- {
- try
- {
- id=Integer.parseInt(br.readLine());
- }
- catch(IOException ie)
- {
- System.out.println("Error");
- }
- if(!process[id-1])
- {
- process[id-1]=true;
- System.out.println("Process Recovered ");
- if(id>coordinator)
- {
- System.out.println("Process "+id+" Bullies Process "+ coordinator);
- coordinator=id;
- }
- }
- else
- {
- System.out.println("Process Already Alive");
- }
- break;
- }
- case 3:
- {
- System.out.println("The Co-ordinator is "+coordinator);
- break;
- }
- case 4:
- {
- ip();
- break;
- }
- case 0:
- {
- break;
- }
- default:
- {
- System.out.println("Invalid Choice");
- break;
- }
- }
- }while(choice!=0);
- }
- public static void main(String args[])
- {
- BullyAlgorithm b=new BullyAlgorithm();
- b.ip();
- b.menu();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement