[LeetCode] Print in Order

아르당·2026년 4월 2일

LeetCode

목록 보기
238/263
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

아래 클래스를 가진다고 가정한다.

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

Foo 객체의 동일한 인스턴스가 세 개의 서로 다른 스레드에 전달된다. 스레드 A는 first(), 스레드 B는 second(), 스레드 C는 third()를 호출한다. second()가 first(), third()가 second() 다음에 실행되도록 하는 메커니즘을 설계하고 프로그램을 수정해라.

Example

#1
Input: nums = [1, 2, 3]
Output: "firstsecondthird"

#2
Input: nums = [1, 3, 2]
Output: "firstthirdsecond"

Constraints

  • nums는 [1, 2, 3]의 순열이다.

Solved

class Foo {

    private Semaphore secondSemaphore;
    private Semaphore thirdSemaphore;

    public Foo() {
        secondSemaphore = new Semaphore(0);
        thirdSemaphore = new Semaphore(0);
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        secondSemaphore.release();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        secondSemaphore.acquire();
        
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        thirdSemaphore.release();
    }

    public void third(Runnable printThird) throws InterruptedException {
        thirdSemaphore.acquire();
        
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글