Implement a blocking queue and print odd/even numbers with threads
Filed under Intuit
Free read 2 of 3Ask about capacity, number of producers and consumers, and whether interruption must be handled. The queue must be thread-safe and avoid busy waiting.
The question
Implement your own bounded blocking queue with put (blocks when full) and take (blocks when empty). Then write a program in which two threads print odd and even numbers alternately up to a limit.
Constraints
- Queue capacity is fixed and positive
- No busy waiting
- Printing order must be 1, 2, 3, ... strictly alternating
Examples
- Input
- limit = 6
- Output
- Thread-odd:1, Thread-even:2, Thread-odd:3, Thread-even:4, Thread-odd:5, Thread-even:6
- Why
- The threads hand over control after each print.
Approach
Ask about capacity, number of producers and consumers, and whether interruption must be handled. The queue must be thread-safe and avoid busy waiting.
Keep a deque and one lock. put waits on a not-full condition while full, take waits on not-empty while empty, and each signals the other after changing the queue. Use a while loop around wait to handle spurious wakeups.
Share a counter and a lock. The odd thread waits until the counter is odd, prints and increments, then notifies; the even thread does the same for even values. Alternatively use two semaphores.
Spurious wakeups, notifyAll versus notify, shutdown and interruption, and fairness. Test with several producers and consumers.
Tips
- What they are testing: Correct use of wait/notify or conditions, and avoiding lost wake-ups and busy waiting.
- Common mistake: Using if instead of while around wait, or polling in a busy loop.
Related Intuit questions
Collected from public candidate posts and coding forums. Updated Nov 2026.