Examples
1. Extending Thread
Thread Print numbers from 1 to 5 in a separate thread with a 1 second pause
package practice;
public class ThreadExamples {
static class NumberPrinter extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
NumberPrinter t = new NumberPrinter();
t.start();
}
}Simulate two independent threads performing tasks
Add 2 numbers in a separate thread
2. Implementing Runnable
Runnable Run multiple tasks using the same class
Access a shared variable counter safely updated by two threads
Add 2 numbers in a separate thread
3. Implementing Callable
Callable Compute factorial of a number and return result
Add 2 numbers in a separate thread
4. Using ExecutorService
ExecutorService Submit 10 print tasks with a thread pool of size 3
Schedule a periodic task every 2 seconds
Add 2 numbers in a separate thread
5. Using CompletableFuture
CompletableFuture Asynchronously fetch user and print welcome message
Chain two async operations with transformation
Combine multiple futures and wait for all
Add 2 numbers in a separate thread
Last updated