00:00

Problem Statement

Input/Output Examples

Visual Explanation

Because the stop markers go to the back of the queue, every task submitted before shutdown still runs.

Approaches

Both approaches create three workers and print the same checks. The first builds on BlockingQueue; the second does the waiting by hand.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw timings; both tabs print the same output.

Complexity Analysis

Submitting is a constant-time queue operation. Only three threads ever exist, no matter how many tasks are submitted.

Interview Tips and Recommended Approach

  • Catch task exceptions inside the worker loop, or one bad task kills a worker for good.
  • Run tasks outside any lock; otherwise only one task runs at a time.
  • Explain poison pills as a clean way to stop consumers without interrupting them mid-task.
  • In real code, use Executors.newFixedThreadPool() or a ThreadPoolExecutor with a bounded queue.

Recommended Approach: BlockingQueue and Poison Pill

Why: it leaves the hard part, waiting and waking, to a well-tested BlockingQueue, so the pool code is short and easy to get right.