Comprehensive Guide to Java Thread Creation

Comprehensive Guide to Java Thread Creation

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

  • Using the Executor framework or Fork/Join framework can lead to better management and utilization of thread resources.
  • Java 8's parallel streams allow for parallel processing of collections in a functional style, abstracting explicit thread management.
  • Lambda expressions simplify the creation of anonymous functions, making it easier to create and manage threads in Java.
  • Introduced in JDK 19 as a preview feature, virtual threads enable developers to improve application performance and scalability.
  • Understanding and effectively using various methods for creating threads can contribute to developing more memory efficient and CPU efficient programs in Java.
  • Callable and Future can return a result from a separate thread, making it suitable for tasks that require result processing.
  • ExecutorService can be shut down to release resources allocated to the thread pool after completing tasks.

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.

  • Since it’s a preview feature, you might need to enable preview features in your IDE and during compilation and execution by using the --enable-preview flag.

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.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了