This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Java classic multithreading problem — chiafan philosopher

Philosophers eating problem: five philosophers share a round table, respectively sitting on five chairs around the table, there are five bowls and five chopsticks on the table, their way of life is alternately thinking and eating. Usually, when a philosopher is thinking and hungry, he will try to take the chopsticks nearest to him. He can only take one chopstick on the left or the right at a time. After he gets one chopstick, he can take the second one. Just finish the meal, put down chopsticks to continue thinking.

This problem is our learning multithreading entry problem, we will discuss this problem.

First, if the philosopher’s access to chopsticks is not restricted, there could be a deadlock,

1. Solution 1: Lock all chopsticks

The first solution is to lock all the chopsticks.

When a philosopher goes to pick up a chopstick, we lock all the chopsticks and block any philosopher who comes to pick up a chopstick until the first philosopher picks up a pair. So you don’t have deadlocks, but this is a very inefficient solution.

2. Solution 2: Lock the two adjacent chopsticks

When a philosopher takes his left chopstick, his right chopstick is not allowed to be taken by other philosophers. This method is to lock the left chopstick in sections. When taking the left chopstick, lock the left and right chopsticks first, thus avoiding the problem of taking only one chopstick.

3. Solution three: One of the scientists is left-handed, so he takes chopsticks from the left, while the others take chopsticks from the right

While a philosopher takes his left chopstick first, other scientists take his right chopstick first.

1. If a left-hander gets the chopsticks, the philosopher on his left cannot get the chopsticks on his right. In this case, the philosopher cannot get a chopstick, and all the chopsticks on his left and right are given to other philosophers.

1. If the left-hander doesn’t get chopsticks, then he is the ren who doesn’t have any chopsticks. If four philosophers have five chopsticks, one of them can definitely get two.

But with this algorithm, only one person can get two chopsticks at a time.

Solution 4: Half the people are left-handed

We can make a slight improvement according to the algorithm of solution 3, for example, “there is one left-handed” is changed to “half left-handed”, and left-handers and left-handers are separated from each other. If represented by odd and even, it means that odd numbers are right-handed and even numbers are left-handed. In this case, the efficiency of the algorithm is better than solution 3.