Skip to content

codes #174

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class AdvancedConcurrencyExample {

public static void main(String[] args) {
    // Create a thread pool with 3 threads
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    List<Future<Long>> futures = new ArrayList<>();

    System.out.println("Submitting tasks...");

    // Submit several complex calculation tasks
    for (int i = 1; i <= 5; i++) {
        Callable<Long> task = new FactorialTask(i);
        Future<Long> future = executorService.submit(task);
        futures.add(future);
    }

    // Retrieve the results using futures
    for (Future<Long> future : futures) {
        try {
            // get() waits if the task is not complete
            System.out.println("Task result: " + future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    // Shut down the executor service
    executorService.shutdown();
    System.out.println("All tasks finished and executor shut down.");
}

}

// A complex task that calculates the factorial of a number
class FactorialTask implements Callable {
private final int number;

public FactorialTask(int number) {
    this.number = number;
}

@Override
public Long call() throws Exception {
    if (number < 0) {
        throw new IllegalArgumentException("Number must be non-negative");
    }
    long result = 1;
    for (int i = 1; i <= number; i++) {
        result *= i;
        // Simulate some hard work
        Thread.sleep(100); 
    }
    System.out.println("Calculated factorial of " + number + " in " + Thread.currentThread().getName());
    return result;
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions