Creating Threads
About
1. Extending the Thread Class
Thread Classpublic class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Thread is running...");
}
}
public class SomeMain {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
// Thread-0 Thread is running...
}
}2. Implementing the Runnable Interface
Runnable Interface3. Using Callable and Future (Return Value from Thread)
Callable and Future (Return Value from Thread)4. Using Anonymous Class
5. Using Lambda Expressions (Java 8+)
6. Using ThreadPoolExecutor (Efficient Thread Management)
ThreadPoolExecutor (Efficient Thread Management)7. Using ForkJoinPool (Parallel Computing)
ForkJoinPool (Parallel Computing)8. Using Virtual Threads (Java 19+)
Virtual Threads (Java 19+)Comparison of Thread Creation Methods
Approach
Flexibility
Can Return Value?
Suitable For
Complexity
Main Thread and New Thread Running Parallelly
Example
How it Works?
Concurrency vs. Parallelism
Why "Both threads execute concurrently" and not "parallelly"?
Example of Concurrency vs. Parallelism
Last updated