Sobes.tech
Junior — Middle

How to organize parallel processing of multiple threads in a program?

sobes.tech AI

Answer from AI

To organize parallel processing of multiple threads in Java, you can use the Thread class or the Runnable interface. It is also more convenient to use a thread pool from ExecutorService, which manages the number of threads and their execution.

Example using ExecutorService:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ParallelProcessing {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3); // pool of 3 threads

        for (int i = 0; i < 5; i++) {
            int taskId = i;
            executor.submit(() -> {
                System.out.println("Executing task " + taskId + " in thread " + Thread.currentThread().getName());
                // task code here
            });
        }

        executor.shutdown(); // stop accepting new tasks
    }
}

This approach allows running multiple tasks simultaneously, efficiently utilizing processor resources.