Thread là đơn vị thực thi cho phép chạy code song song. Mỗi Java app đã có main thread; tạo thêm thread để task không block main.
4 cách tạo, từ cũ → hiện đại:
1. Extend Thread (hiếm dùng — chiếm slot extends).
2. Implement Runnable (cổ điển):
new Thread(() -> System.out.println("hi"), "worker-1").start();3. Callable + ExecutorService (Java 5+) — trả kết quả qua Future:
ExecutorService exec = Executors.newFixedThreadPool(4);
Future<String> f = exec.submit(() -> "result");
exec.shutdown();**4.
Virtual Threads (Java 21 — Loom) — cực kỳ nhẹ**, hàng triệu thread trên ít OS thread:
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) exec.submit(() -> fetchFromAPI());
}Lý tưởng cho I/O-bound; không giúp CPU-bound.
Quy tắc:
- start() tạo thread mới; run() chạy ngay trên thread hiện tại → KHÔNG concurrency.
- Luôn shutdown ExecutorService (hoặc try-with-resources).
- 2026 default: I/O-bound → Virtual Threads; CPU-bound → fixed thread pool sized to cores.
- Đừng extends Thread; tránh new Thread() thủ công trong production.
A thread is a unit of execution allowing code to run in parallel. Every Java app has a main thread; you create more threads so tasks do not block main.
4 ways, oldest → modern:
1. Extend Thread (rare — wastes the single extends slot).
2. Implement Runnable (classic):
new Thread(() -> System.out.println("hi"), "worker-1").start();3. Callable + ExecutorService (Java 5+) — returns a result via Future:
ExecutorService exec = Executors.newFixedThreadPool(4);
Future<String> f = exec.submit(() -> "result");
exec.shutdown();**4.
Virtual Threads (Java 21 — Loom) — extremely lightweight**, millions of threads atop few OS threads:
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) exec.submit(() -> fetchFromAPI());
}Ideal for I/O-bound; does not help CPU-bound.
Rules:
- start() creates a new thread; run() runs on the current thread → NO concurrency.
- Always shut down ExecutorService (or use try-with-resources).
- 2026 default: I/O-bound → Virtual Threads; CPU-bound → fixed thread pool sized to cores.
- Avoid extends Thread; avoid raw new Thread() in production.