Master platform threads, virtual threads (Project Loom), thread creation, Runnable and Callable interfaces, thread lifecycle, and thread states for the OCP 21 exam.
Table of Contents
1. Threads Overview
A thread is a lightweight process that can execute code concurrently. Java supports both platform threads (OS threads) and virtual threads (lightweight threads).
1.1 Platform Threads vs Virtual Threads
| Aspect | Platform Threads | Virtual Threads |
|---|---|---|
| Resource Usage | Heavy (OS thread) | Lightweight (managed by JVM) |
| Scalability | Limited (thousands) | Millions |
| Creation | new Thread() | Thread.ofVirtual() |
2. Creating Threads
2.1 Extending Thread Class
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
MyThread thread = new MyThread();
thread.start(); // Start the thread
2.2 Implementing Runnable
Example:
// Using Runnable
Runnable task = () -> System.out.println("Running: " + Thread.currentThread().getName());
Thread thread = new Thread(task);
thread.start();
// Using lambda
Thread thread2 = new Thread(() -> System.out.println("Lambda thread"));
thread2.start();
3. Runnable and Callable Interfaces
3.1 Runnable Interface
Example:
// Runnable - no return value, no checked exceptions
Runnable task = () -> {
System.out.println("Executing task");
// No return value
};
Thread thread = new Thread(task);
thread.start();
3.2 Callable Interface
Example:
// Callable - returns value, can throw checked exceptions
Callable<Integer> task = () -> {
Thread.sleep(1000);
return 42;
};
// Callable is used with ExecutorService
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);
Integer result = future.get(); // Blocks until result is available
4. Thread Lifecycle and States
4.1 Thread States
- NEW: Thread created but not started
- RUNNABLE: Thread is executing or ready to execute
- BLOCKED: Thread blocked waiting for monitor lock
- WAITING: Thread waiting indefinitely for another thread
- TIMED_WAITING: Thread waiting for specified time
- TERMINATED: Thread has completed execution
Example:
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(thread.getState()); // NEW
thread.start();
System.out.println(thread.getState()); // RUNNABLE
Thread.sleep(100);
System.out.println(thread.getState()); // TIMED_WAITING
thread.join();
System.out.println(thread.getState()); // TERMINATED
5. Virtual Threads (Java 21)
Virtual threads (Project Loom) are lightweight threads managed by the JVM, allowing millions of concurrent threads.
5.1 Creating Virtual Threads
Example:
// Create virtual thread
Thread virtualThread = Thread.ofVirtual()
.name("virtual-thread-", 0)
.start(() -> System.out.println("Virtual thread"));
// Using Executors.newVirtualThreadPerTaskExecutor()
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
executor.submit(() -> System.out.println("Task in virtual thread"));
executor.shutdown();
// Virtual threads are ideal for I/O-bound tasks
for (int i = 0; i < 10000; i++) {
Thread.ofVirtual().start(() -> {
// I/O operation
});
}
6. Exam Key Points
Critical Concepts for OCP 21 Exam:
- Thread: Lightweight process for concurrent execution
- Platform Thread: OS-managed thread (heavyweight)
- Virtual Thread: JVM-managed thread (lightweight, Java 21)
- Runnable: Interface for tasks without return value
- Callable: Interface for tasks with return value
- Thread States: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
- start(): Starts thread execution
- run(): Executes thread code (don't call directly)
- join(): Waits for thread to complete
- getState(): Returns current thread state
- Virtual Threads: Ideal for I/O-bound tasks, millions can be created
0 Comments