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

推荐订阅源

月光博客
月光博客
N
Netflix TechBlog - Medium
罗磊的独立博客
博客园 - 聂微东
美团技术团队
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园_首页
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
Microsoft Azure Blog
Microsoft Azure Blog
量子位
SecWiki News
SecWiki News
F
Fortinet All Blogs
J
Java Code Geeks
S
SegmentFault 最新的问题
V
V2EX
Martin Fowler
Martin Fowler
F
Full Disclosure
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
S
Security Affairs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
Kaspersky official blog
S
Secure Thoughts
S
Schneier on Security
MongoDB | Blog
MongoDB | Blog
博客园 - 三生石上(FineUI控件)
Cloudbric
Cloudbric
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
V2EX - 技术
V2EX - 技术
H
Hackread – Cybersecurity News, Data Breaches, AI and More
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
C
Check Point Blog
T
The Blog of Author Tim Ferriss
D
DataBreaches.Net
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
Google Developers Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tenable Blog
博客园 - 【当耐特】

博客园 - 北叶青藤

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: