DEV Community 👩‍💻👨‍💻

Ezekiel nwuguru
Ezekiel nwuguru

Posted on

DAY 4: Print in order

Hey! It's day 4 of I4G 10 days of coding challenge. Today's task was to implement a code that prints in order.

Thought process:

  • 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.

  • Algorithm:

  1. Create two instances of the Semaphore class: semaphore1 and semaphore2
  2. Add semaphore1.release() to the end of the first thread
  3. Add semaphore1.acquire() to the beginning of the second thread
  4. Add semaphore2.release() to the end of the second thread
  5. 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/

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠