In the previous post I discussed about multi-threading concepts and provided a case study to understand the principles better. In this post the solution of the case study is given with detailed explanation about it.
As mentioned, the first thing that program should do is to categorize mails, this is rather simple and no need to involve multi-threading and it can be resolved with a simple if, else condition.
Check the below sample code for better understanding,
We have categorized the main queue to 4 groups (vectors). Now it is time to send each mail man (vector) to operate separately (run in a separate thread) the same task which is mails distribution. However, we should bear in mind about the last portion of the case study which refers to security man waiting, therefore, we need to keep track of the threads and to this so need to create an array to holds thread reference. Check the below code,
The only remaining and most challenging part is to avoid mailmen (threads) to access to the notebook (resource) at the same time. If one resource will be access at the same time, race condition might occur and the value of one resource might be changed without notifying others resource holders. To avoid such a problem the best approach is using locking mechanism in which resource cannot be allocated to more than one thread at the same time. This is done with using synchronized keyword. The entire operation of mail main is written in a separate class file which is as well.
As you can see multi-threading is not as cumbersome as it seems, just you need to learn the basic concept first and find an example (preferably real world) to implement to become master of it 😉