1+ /* Program for the classic dining philosopher problem in operating system */
12package javacodes ;
23
34
@@ -8,14 +9,15 @@ public static void main(String[] args){
89 int x =10 ;
910
1011 Log .msg (String .valueOf (x ));
11-
12+ /* Initializing 5 chopsticks */
1213 Chopstick [] chopistics = new Chopstick [5 ];
1314
1415 for (int i =0 ; i < chopistics .length ; i ++){
1516
1617 chopistics [i ] = new Chopstick ("C: " +i );
1718 }
1819
20+ // Initialising five philosophers and their corresponding positions
1921 Philosopher [] philosophers = new Philosopher [5 ];
2022
2123 philosophers [0 ] = new Philosopher ("P: 0 - " , chopistics [0 ], chopistics [1 ]);
@@ -39,7 +41,7 @@ public static void main(String[] args){
3941 }
4042}
4143
42-
44+ //Class for philosophers
4345class Philosopher extends Thread
4446{
4547 private Chopstick leftChopistick ;
@@ -63,6 +65,9 @@ public Philosopher ( String name, Chopstick left, Chopstick right){
6365
6466 public void eat ()
6567 {
68+ // While eating, every philosopher pics up the left chopstick first and the the right chopstick. If the philosopher gets both the chopsticks
69+ // he eats for 1000 ms and then releases the chopsticks
70+ //Else he waits for chopsticks to be free
6671 if (! leftChopistick .used ){
6772
6873 if (!rightChopistick .used ){
@@ -116,6 +121,7 @@ public static void Delay(int ms){
116121 }
117122}
118123
124+ //Class for chopstick that provides use and release functionalities to pilosophers
119125class Chopstick {
120126
121127 public boolean used ;
@@ -126,13 +132,15 @@ public Chopstick(String name){
126132
127133 this .name = name ;
128134 }
129-
135+ //method to reserve the chopstick for use
130136 public synchronized void take () {
131137
132138 Log .msg ("Used :: " + name );
133139
134140 this .used = true ;
135141 }
142+
143+ //method to release the chopstick for use
136144 public synchronized void release () {
137145
138146 Log .msg ("Released :: " + name );
0 commit comments