Add multithreading module: odd-even, ping-pong, ordered threads, deadlock detection and fixes, virtual-thread variants (25 tests)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7rnC7jppGGdHGESvy
This commit is contained in:
Claude
2026-10-28 18:10:23 +00:00
parent f80e1079a8
commit 94306c50ab
29 changed files with 1021 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
# multithreading
Classic multithreading interview programs in plain Java 25, each runnable and each pinned by a
JUnit test with a hard timeout (no `sleep()` is used to synchronise anything). Companion to
[Java Multithreading Programs for Interviews](https://ankurm.com/java-multithreading-programs-interview-odd-even-ping-pong-deadlock/).
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | 25.0.5+8 (Temurin LTS), `--release 25` | `java -version` |
| JUnit Jupiter | 6.1.3 | same version as the other modules in this repo |
| Maven | 3.9.11 | `mvn -version` |
## Run it
```bash
cd multithreading
./scripts/run.sh odd-even # also: ping-pong | ordered | deadlock | virtual
mvn test # 25 tests
./scripts/run-all.sh # regenerates everything in output/
```
## Programs
| Question | Class | Technique |
|---|---|---|
| Odd-even printing | `OddEvenWaitNotify`, `OddEvenSemaphore`, `OddEvenLockCondition` | `synchronized`+`wait/notifyAll`; two `Semaphore`s; `ReentrantLock`+2 `Condition`s |
| Ping-pong | `PingPong` | `ReentrantLock`+2 `Condition`s, boolean turn flag |
| Ordered threads | `OrderedThreads` | `CountDownLatch` chain; `join()` chain; `Semaphore` ring (3 or 1,000 threads) |
| Deadlock | `Transfers`, `DeadlockScenario`, `DeadlockDetector` | naive vs lock ordering vs `tryLock(timeout)`; detection by `ThreadMXBean.findDeadlockedThreads` |
| Virtual threads | every class takes a `ThreadKind` (`PLATFORM` / `VIRTUAL`) | same code, both thread types |
Support: `Group` starts named threads and waits with a deadline (a hang becomes a failing test).
## Captured output (`output/`)
| File | What it shows |
|---|---|
| `01-odd-even.txt` | the three odd-even implementations, 1..10 |
| `02-ping-pong.txt` | 4 rounds of ping/pong |
| `03-ordered-threads.txt` | T3,T2,T1 started in that order, run T1,T2,T3; round-robin of 3 threads |
| `04-deadlock.txt` | real `findDeadlockedThreads` report, both fixes, and virtual threads being invisible to it |
| `05-virtual-single-carrier.txt` | wait/notify and 1,000 virtual threads on ONE carrier thread |
| `06-test-results.txt` | every test name, pass/fail |
## License
MIT, see the repository root.