dining philosophers problem in java

Dining Philosophers Problem: Consider five philosophers who spend time in thinking and eating.the philosophers share a common circular table surrounded by five chairs,each belonging to one philosopher.In the center of the table is a bowl of rice and the table is laid with five single chopsticks.when a philosopher thinks she does not interacts with her colleagues.From time to time philosopher gets hungry and tries to pick up the two chopsticks that are between her left and right philosopher. philosopher may pick up only one chopstick at a time.Obviously,she cannot pick chopstick in hand of neighbor.When hungry philosopher has both her chopstick at the same time she eats without releasing her chopstick.When she is finished eating she puts down chopstick and start thinking.


import java.io. * ;
class Philo {
	int state[] = new int[5];
	int thinking,
	eating,
	hungry;
	void Op() {
		thinking = 0;
		eating = 1;
		hungry = 2;
	}
	public void pickup(int i) {
		state[i] = 2;
		System.out.println("Philosopher " + i + " is hungry");
		test(i);
		if (state[i] == 2) System.out.println("Philosopher " + i + " is waiting");
	}
	public void putdown(int i) {
		if (state[i] == 1) {
			state[i] = 0;
			System.out.println("Philosopher" + i + " is thinking");
			test((i + 1) % 5);
			test((i + 5) % 5);
		}
	}

	public void test(int i) {
		if (state[i] == 2 & amp; & amp; state[(i + 1) % 5] != 1 & amp; & amp; state[(i + 4) % 5] != 1) {
			state[i] = 1;
			System.out.println("philosopher " + i + " is eating");
		}
	}
}
class Philosopher {
	public static void main(String args[]) throws IOException {
		Philo d = new Philo();
		for (int i = 0; i & lt; 5; i++)
		d.pickup(i);
		for (int i = 0; i & lt; 5; i++)
		d.putdown(i);
	}
}

/* Output for dining philosophers problem

Philosopher 0 is hungry
philosopher 0 is eating
Philosopher 1 is hungry
Philosopher 1 is waiting
Philosopher 2 is hungry
philosopher 2 is eating
Philosopher 3 is hungry
Philosopher 3 is waiting
Philosopher 4 is hungry
Philosopher 4 is waiting
Philosopher0 is thinking
Philosopher2 is thinking
philosopher 3 is eating
Philosopher3 is thinking
philosopher 4 is eating
Philosopher4 is thinking
*/

Facing difficulties in understanding the program ?

Ask Your Queries in Comment Box

You may also like...

1 Response

  1. Dheeraj says:

    Here Philosopher1 never gets to eat.

Leave a Reply

Your email address will not be published. Required fields are marked *