Cover Image for Performing multiple task
164 views

Performing multiple task

Performing multiple tasks in Java often involves using multi-threading or asynchronous programming to execute tasks concurrently. This allows different parts of the program to run simultaneously, improving performance and responsiveness. Here are some common approaches to performing multiple tasks:

  1. Multi-Threading: Create multiple threads to execute tasks concurrently. Java provides the Thread class and the Runnable or Callable interfaces to implement multi-threading. Each thread runs independently, and you can synchronize access to shared resources to ensure thread safety.
public class MultiThreadExample {
    public static void main(String[] args) {
        Runnable task1 = () -> {
            // Task 1 logic here
            System.out.println("Task 1 is running.");
        };

        Runnable task2 = () -> {
            // Task 2 logic here
            System.out.println("Task 2 is running.");
        };

        Thread thread1 = new Thread(task1);
        Thread thread2 = new Thread(task2);

        thread1.start();
        thread2.start();
    }
}
  1. Executor Framework: Use the Executor framework provided by the java.util.concurrent package. It manages thread pools and simplifies the management of multiple tasks, improving resource utilization and performance.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        executor.execute(() -> {
            // Task 1 logic here
            System.out.println("Task 1 is running.");
        });

        executor.execute(() -> {
            // Task 2 logic here
            System.out.println("Task 2 is running.");
        });

        executor.shutdown();
    }
}
  1. CompletableFuture: Use CompletableFuture to perform asynchronous tasks and handle results when they complete.
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            // Task 1 logic here
            return "Task 1 completed.";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            // Task 2 logic here
            return "Task 2 completed.";
        });

        CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2);
        allOf.thenRun(() -> {
            System.out.println(future1.join());
            System.out.println(future2.join());
        });
    }
}
  1. Parallel Streams: Use parallel streams to perform operations concurrently on collections.
import java.util.Arrays;

public class ParallelStreamExample {
    public static void main(String[] args) {
        Arrays.asList("Task 1", "Task 2").parallelStream().forEach(task -> {
            // Task logic here
            System.out.println(task + " is running.");
        });
    }
}

Each approach has its advantages and is suitable for different scenarios. The choice depends on the nature of tasks, the required level of control, and the complexity of synchronization. When performing multiple tasks, it’s essential to handle thread synchronization, potential race conditions, and data consistency to ensure the correctness and reliability of the application.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS