-
Notifications
You must be signed in to change notification settings - Fork 694
Open
Description
import java.util.concurrent.*;
import java.math.BigInteger;
public class AdvancedConcurrency {
public static BigInteger calculateFactorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
// Submitting a Callable task to the executor
Future<BigInteger> futureResult = executor.submit(() -> {
System.out.println("Calculation started in a separate thread...");
BigInteger factorial = calculateFactorial(50); // A moderately large number
Thread.sleep(1000); // Simulate some delay
return factorial;
});
// Main thread continues execution
System.out.println("Main thread is doing other work...");
try {
// Get the result from the Future (this call blocks until the result is ready)
BigInteger result = futureResult.get();
System.out.println("Result received: " + result.toString().substring(0, 50) + "...");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown(); // Always shut down the executor
}
}
}
Metadata
Metadata
Assignees
Labels
No labels