-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdining_philosopher.java
More file actions
55 lines (53 loc) · 1.16 KB
/
dining_philosopher.java
File metadata and controls
55 lines (53 loc) · 1.16 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
class philosopher{
//value of ststus (0,thinking) (1,hungry) (2,eating)
int status;
int philo_num;
philosopher obj[];
int n;
philosopher(int philo_num,philosopher obj[],int n){
this.philo_num=philo_num;
this.obj=obj;
this.n=n;
status=0;
}
void putdown(){
status=0;
System.out.println(philo_num+" is Thinking");
test((philo_num-1)%n);
test((philo_num+1)%n);
}
void pickup(){
status=1;
System.out.println(philo_num+" is hungry");
test(philo_num);
}
void test(int i){
if(status==1&&obj[(i+1)%n].status!=2&&obj[(i-1)%n].status!=2){
status=2;
System.out.println(i+" is eating");
}
}
}
class empty_class{}
class create_thread{
public static void main(String[] ars){
philosopher obj[]=new philosopher[5];
for(int i=0;i<5;i++)
obj[i]=new philosopher(i,obj,5);
//Creating thread
empty_class sync=new empty_class();
final int i;
for(i=0;i<5;i++){
Thread th=new Thread(){
public void run(){
while(true){
synchronized(sync){obj[i].pickup();}
try{Thread.sleep(1000);}catch(Exception e){}
synchronized(sync){obj[i].putdown();}
}
}
};
th.start();
}
}
}