dining philosophers problem using multithreading in java

Dining Philosopher’s Problem is one of the problem classic problems of multi threading and thread synchronization. 

Statement and Explanation

Here we have five philosophers sitting around a dining table which has five plates and five forks as shown in the image below. All they do is thinking and eating.

Here forks are the shared objects. Each fork is shared between two philosophers.

They will be thinking when they do not have access to both the forks. When they get both forks, they will eat. Our task is to synchronise this sharing of forks so that circular wait do not happens. In circular wait, every philosopher gets a fork and will be waiting for another fork which is acquired by another philosopher.

If this happens, no one gets to eat and will be waiting indefinitely.

java program to implement dining philosophers problem

Here we need to create five threads, one for each philosopher. Also, we need to create five fork objects.

 For each philosopher, we give two shared fork objects. Everyone gets the forks in the order of left first and right next except last philosopher. 

what’s the reason might be?

The reason is a circular wait condition might arise if forks given in Left first right next order. I recommend to experiment and try it out. 

The main logic is initially every philosopher will be thinking for a random amount of time. This will make someone to get a kick start instead of following the same order every time.

Here we are using synchronised block to get the access to monitor. In the previous examples we have used synchronised method.

 Here, the philosopher acquires left fork first and then right fork next and when he finishes eating, he will relieve the access in the reverse order.

The same will go on indefinitely. Do experiment with the code and reason the random sleep time.


The output looks something like this.

dining philosophers problem java semaphore


Post a Comment