Comprehensive Guide to Java Thread Creation
?? Saral Saxena ??????
?11K+ Followers | Linkedin Top Voice || Associate Director || 14+ Years in Java, Microservices, Kafka, Spring Boot, Cloud Technologies (AWS, GCP) | Agile , K8s ,DevOps & CI/CD Expert
We will discuss various methods for creating threads in Java programming, including extending the Thread class, implementing the Runnable interface, using the Executor framework, Callable and Future, Parallel Streams, Fork/Join framework, Lambda expressions, Completable Future for asynchronous tasks, and Virtual Threads in JDK 19.
Opinions are
How do you create threads in Java?
we can create threads in many ways, I would disucss all the ways we can spawn threads directly or indirectly. All the below methods create threads in some or the other ways , there are som more direct ways of creating and using threads in Java and there are much more abstraction available in order to create threads to achieve concurrency like Executor framework and Completable Future.
By extending the thread class.
class NewThread extends Thread {
public void run() {
// Code to execute in the new thread
}
}
// Creating and starting a thread
MyThread t = new MyThread();
t.start();
Implementing the Runnable interface.
class RannableThread implements Runnable {
public void run() {
// Code to execute in the new thread
}
}
// Creating and starting a thread
Thread t = new Thread(new MyRunnable());
t.start();
Using executor Framework.
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new MyRunnable());
executor.shutdown();
Using callable and future.
Callable<Integer> callableTask = () -> {
// Task code, which returns a result
return 42;
};
Future<Integer> future = executor.submit(callableTask);
// Later, you can retrieve the result
Integer result = future.get();
Using Parallel Streams:
Introduced in Java 8, parallel streams allow for parallel processing of collections in a functional style, abstracting away explicit thread management.
List<String> demoList = Arrays.asList("ABE", "BAC", "CSD", "DER", "ERT");
myList.parallelStream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.forEach(System.out::println);
Fork/Join Framework:
ForkJoinPool forkJoinPool = new ForkJoinPool(4); // Pool with 4 threads
Long result = forkJoinPool.invoke(new MyRecursiveTask(data));
领英推荐
Using Lambda Expression
Thread thread = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try {
// Pausing for half a second
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
Using Completable Future to run an async task
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureExample {
public static void main(String[] args) {
// Using the common ForkJoinPool
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// Task to run asynchronously
System.out.println("Running asynchronously in " + Thread.currentThread().getName());
});
// Wait for the CompletableFuture to complete
future.join();
}
}
Supplying a Value and processing that Asynchronously.
→Supply a Task to run in another thread.
→Process the results.
→ wait for all operations to complete before moving forward.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Simulate a long-running task
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
// Handle interruption
}
return "Result of the asynchronous computation";
});
// Process the result of the computation
future.thenAccept(result -> System.out.println(result));
future.join(); // Wait for all operations to complete
Using a custom Executor:
→Creating a Customer Executor
→Running asynchronously differnt tasks in threads.
→Joining all the task as a blocking operation.
→ Shutting down the executor.
ExecutorService executor = Executors.newCachedThreadPool();
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running asynchronously in " + Thread.currentThread().getName());
}, executor);
future.join();
executor.shutdown(); // Remember to shut down the executor
Virtual Threads As well
In order to create Virtual Threads Ensure you are using JDK 19 or later, as virtual threads are introduced in Java 19 as a preview feature.
public class VirtualThread {
public static void main(String[] args) {
Thread virtualThread = Thread.ofVirtual().start(() -> {
System.out.println("Running in a virtual thread: " + Thread.currentThread().getName());
});
// Wait for the virtual thread to complete its execution
virtualThread.join();
}
}
Threads are everywhere and are very prevalent in programming and efficient usage of threads is very helpful in order to create memory efficient and CPU efficient programs.