Java Programs›Multithreading

🧵Java Multithreading Programs

Concurrency questions separate junior from senior Java developers. These programs build up from creating a single thread to coordinating several, and every one is written to print the same output on each run, so the behaviour is easy to follow.20 programs · each with full code, output and a step-by-step explanation

Most Asked in Interviews

🔍
Advanced
09
Avoid Deadlock with Lock Ordering
Prevents a bank-transfer deadlock by always acquiring the two account locks in the same order.
advancedConcurrency
View Program →
10
Combine Async Results with CompletableFuture
Runs two lookups asynchronously and combines their results with CompletableFuture.thenCombine.
advancedConcurrency
View Program →
11
Count Words Concurrently Using ConcurrentHashMap
Counts word frequencies across three threads at once with ConcurrentHashMap.merge, without any explicit locks.
advancedConcurrency
View Program →
12
Implement a Bounded Blocking Queue
Builds a fixed-capacity queue whose put waits when full and whose take waits when empty, using ReentrantLock and Conditions.
advancedConcurrency
View Program →
13
Implement a Rate Limiter
Limits how often requests are accepted using the token bucket algorithm, allowing short bursts but a steady average rate.
advancedConcurrency
View Program →
14
Implement a Thread Pool
Builds a fixed-size thread pool from scratch with worker threads that take tasks from a shared BlockingQueue.
advancedConcurrency
View Program →
15
Implement a Thread-Safe Singleton
Creates exactly one instance of a class even when several threads request it at once, using double-checked locking.
advancedConcurrency
View Program →
16
Print Odd and Even Numbers Using Two Threads
Makes two threads take turns printing 1 to 10, one printing odd numbers and the other even, with wait and notifyAll.
advancedConcurrency
View Program →
17
Producer-Consumer Problem
Coordinates a producer and a consumer thread through a bounded BlockingQueue.
advancedConcurrency
View Program →
18
Run Tasks with ExecutorService
Submits factorial tasks to a fixed thread pool and collects the results through Futures.
advancedConcurrency
View Program →
19
Use the Fork/Join Framework to Sum an Array
Sums 100,000 numbers by recursively splitting the array into halves that run in parallel on a ForkJoinPool.
advancedConcurrency
View Program →
20
Use a ReadWriteLock for a Shared Cache
Lets many threads read a shared price cache at once while writers get exclusive access, using ReentrantReadWriteLock.
advancedConcurrency
View Program →