Hey! It's day 4 of I4G 10 days of coding challenge. Today's task was to implement a code that prints in order.
Understanding of problem: My first approach in solving this challenge was to understand the problem. Understanding of the problem paved way for me to brainstorm on possible solutions. The way an operating system schedules a thread varies; we cannot predict the order in which the thread can be executed. The task here is to modify a code such that the first thread is always executed first, the second executed second and so on.
Solution: To achieve this, I utilized one of the Java classes called Semaphore. Semaphore helps to restrict the number of threads that can access some (physical or logical) resource. The Semaphore class maintains a set of permits. It utilizes the acquire() method to block further executions until a permit is available. It uses the release() method to give a permit, thus releasing a potentially blocking acquirer.
- Create two instances of the Semaphore class: semaphore1 and semaphore2
- Add semaphore1.release() to the end of the first thread
- Add semaphore1.acquire() to the beginning of the second thread
- Add semaphore2.release() to the end of the second thread
- Add semaphore2.acquire() to the beginning of the third thread
Check out the full java code here: Print in Order - LeetCode https://leetcode.com/problems/print-in-order/submissions/