惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
雷峰网
雷峰网
S
SegmentFault 最新的问题
博客园 - 【当耐特】
博客园_首页
量子位
爱范儿
爱范儿
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
V
V2EX
美团技术团队
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
博客园 - 聂微东
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
宝玉的分享
宝玉的分享
WordPress大学
WordPress大学
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1242. Web Crawler Multithreaded Python Multi-threading bot ip Log Rate Limiter Same Word of HTML Labels Most Frequent Call Chain remove prefix in a words list 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Keyword Tagging in Reviews with Overlapping Matches Retryer Function Implementation 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 1650. Lowest Common Ancestor of a Binary Tree III 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
1114. Print in Order
北叶青藤 · 2026-07-16 · via 博客园 - 北叶青藤

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.

Example 1:

Input: nums = [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.

Example 2:

Input: nums = [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output. 

Constraints:

  • nums is a permutation of [1, 2, 3].

Solution 1: Lock (Most Common)

The idea is simple:

  • first() runs immediately.
  • second() waits until first() finishes.
  • third() waits until second() finishes.
from threading import Lock

class Foo:
    def __init__(self):
        self.lock2 = Lock()
        self.lock3 = Lock()

        self.lock2.acquire()
        self.lock3.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        printFirst()
        self.lock2.release()

    def second(self, printSecond: 'Callable[[], None]') -> None:
        with self.lock2:
            printSecond()
            self.lock3.release()

    def third(self, printThird: 'Callable[[], None]') -> None:
        with self.lock3:
            printThird()

Solution 2: Semaphore (Very Common)

This is probably the cleanest solution.

Why Semaphore(0)?

Initial permits:

Calling

blocks until someone calls

So


Solution 3: Condition Variable

Here:

  • stage == 1 → first should run
  • stage == 2 → second should run
  • stage == 3 → third should run

Always use a while loop instead of if around wait() to handle spurious wakeups.


Solution 4: Event (Simplest)

Python's Event is designed exactly for "wait until something happens."

An Event behaves like a boolean flag:

  • Initially False.
  • wait() blocks until the flag becomes True.
  • set() changes the flag to True and wakes all waiting threads.

Interview rule of thumb

When designing concurrent systems:

  • Need mutual exclusion?
    Lock
  • Need N threads/resources at the same time?
    Semaphore
  • Need to wait for a condition/state change?
    Condition
  • Need one thread to broadcast "I am ready/done/stopped"?
    Event

A good mental model: