-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbully_Algorithm.java
145 lines (98 loc) · 2.57 KB
/
bully_Algorithm.java
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package Bully;
import java.io.*;
import java.util.Random;
public class bully_Algorithm {
static class Message{
Participant process;
Message(Participant p){
process=p;
}
}
static class MessageBox{
int entries,maxEntries;
Object[] elements;
public MessageBox(int number)
{
maxEntries=number;
elements=new Object[maxEntries];
entries=0;
}
synchronized void send(Object msg)throws InterruptedException{
while(entries==maxEntries)
wait();
elements[entries]=msg;
entries=entries+1;
notifyAll();
}
synchronized Object recieve()throws InterruptedException{
while(entries==0)
wait();
Object x;
x=elements[0];
for(int i=1;i<entries;i++)
elements[i-1]=elements[i];
entries=entries-1;
notifyAll();
return x;
}
}
static class Participant extends Thread{
MessageBox inbox;
MessageBox[]neighbour;
int value;
Participant leader;
Participant self;
public void run(){
leader=this;
self=this;
for(int i=0;i<neighbour.length;i++)
try{
neighbour[i].send(new Message(self));
}catch(Exception e){}
try{while(true){
Message m=(Message)inbox.recieve();
System.out.println(value+"Recieves "+m.process.value);
if(m.process.value>leader.value)
leader=m.process;
}
}catch(Exception e){}
}
}
public static void main(String args[])throws IOException{
final int processNo=7;
final int[] value=new int[processNo];
Random randomGenerator=new Random();
//Assigning Random ID to the process
for(int i=0;i<value.length;i++){
value[i]=randomGenerator.nextInt(100);
}
Participant[] processes=new Participant[processNo];
MessageBox[] box=new MessageBox[processNo];
for(int i=0;i<processNo;i++){
processes[i]=new Participant();
processes[i].value=i;
box[i]=new MessageBox(4);
}
for(int i=0;i<processNo;i++){
processes[i].inbox=box[i];
processes[i].neighbour=new MessageBox[processNo];
}
for(int i=0;i<processNo;i++){
for(int j=0;j<processNo;j++)
processes[i].neighbour[j]=processes[j].inbox;
}
for(int i=0;i<processNo;i++)
processes[i].start();
try{
Thread.sleep(100);
}catch(Exception e){}
for(int i=0;i<processNo;i++)
processes[i].interrupt();
for(int i=0;i<processNo;i++)
{
if(processes[i].leader!=null)
System.out.println(processes[i].value+"Elected Leader is "+processes[i].leader.value);
}
System.exit(0);
}
}