diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/ExecuteExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/ExecuteExample.java new file mode 100644 index 0000000000..6b6d6e3e8a --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/ExecuteExample.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ExecuteExample { + public static void main(String[] args) { + ExecutorService executorService = Executors.newFixedThreadPool(2); + // Task using Runnable + Runnable task = () -> { + int[] numbers = { 1, 2, 3, 4, 5 }; + int sum = 0; + for (int num : numbers) { + sum += num; + } + System.out.println("Sum calculated using execute:" + sum); + }; + // Submit the task using execute + executorService.execute(task); + executorService.shutdown(); + + } + +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/SubmitExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/SubmitExample.java new file mode 100644 index 0000000000..cd715edcc0 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/SubmitExample.java @@ -0,0 +1,31 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class SubmitExample { + public static void main(String[] args) { + ExecutorService executorService = Executors.newFixedThreadPool(2); + Callable task = () -> { + int[] numbers = { 1, 2, 3, 4, 5 }; + int sum = 0; + for (int num : numbers) { + sum += num; + } + return sum; + }; + // Submit the task and obtain a Future + Future result = executorService.submit(task); + try { + // Get the result + int sum = result.get(); + System.out.println("Sum calculated using submit:" + sum); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + executorService.shutdown(); + } +} \ No newline at end of file