Data Structures and Algorithms (Day-4 #I4G10DaysOfCodeChallenge)
Print in Order Challenge
Table of contents
Introduction
Today, the forth day of this challenge came as a very complicated one which had to do with multi-threading. Here's the challenge.
Challenge
Suppose we have a class:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().
Note:
We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.
Click Here to view the challenge on Leetcode.
Explanation & Solution
What is required from this challenge is to ensure that only when thread A is completely executed, before thread B is executed. Thread C executes only when thread B is completely executed.
Now let's assume a scenario where there are 3 persons, person A, person B, and person C to use a restroom. Person A enters the restroom first while the others wait. Person B only enters the restroom when person A is done and comes out. Then only when person B is done with the restroom, person C enters.
With the above idea, I solved today's challenge. However, it was tricky and required understanding threading (single-threading and multi-threading) in programming.
Thanks for reading.