DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Deep Dive Into Java Executor Framework
  • Configuring Spark-Submit
  • Apache Airflow Configuration and Tuning
  • Efficient Task Management: Building a Java-Based Task Executor Service for Your Admin Panel

Trending

  • Lift-and-Shift vs. Modernize: A Decision Framework for Enterprise Workloads
  • The Invisible OOMKill: Why Your Java Pod Keeps Restarting in Kubernetes
  • Going Stateless: Scaling MCP Servers to Cloud-Native Java and HTTP
  • Implementing Asynchronous Communication Between Microservices Using Kafka and Spring Boot

Print Even and Odd Numbers Using (Two Threads) Completable Future and Executor Service

A code snippet to print Even and Odd numbers using multi-threading.

By 
Swyrik Thupili user avatar
Swyrik Thupili
·
Sep. 03, 21 · Code Snippet
Likes (4)
Comment
Save
Tweet
Share
9.4K Views

Join the DZone community and get the full member experience.

Join For Free

You might have seen this question being asked in so many interviews. 

We are going to achieve this using Java 8 completable future and executor service.

  1. We have created two single-thread executors and assigned a name to them.
  2. Using IntStream we are iterating from 1 to 101. 
  3. Using two completable futures to check odd or even and calling join after the call so that the completable future will finish its execution.
  4. Shutting down the executor services in the end.
Java
 
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class Solution{

	public static void main(String[] args) {
		ExecutorService firstExecutorService = Executors.newSingleThreadExecutor(r -> {
			Thread t = new Thread(r);
			t.setName("first");
			return t;
		});
		ExecutorService secondExecutorService = Executors.newSingleThreadExecutor(r -> {
			Thread t = new Thread(r);
			t.setName("second");
			return t;
		});
		IntStream.range(1, 101).forEach(num -> {
			CompletableFuture<Integer> thenApplyAsync = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {

				if (x % 2 == 1) {
					System.out.println(x + " " + Thread.currentThread().getName());
				}
				return num;
			}, firstExecutorService);
			thenApplyAsync.join();

			CompletableFuture<Integer> thenApplyAsync2 = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
				if (x % 2 == 0) {
					System.out.println(x + " " + Thread.currentThread().getName());
				}
				return num;
			}, secondExecutorService);
			thenApplyAsync2.join();
		});
      
		firstExecutorService.shutdown();
		secondExecutorService.shutdown();
	}

}

If you run the above code you will see the following logs in the console.

Output


Executor (software)

Opinions expressed by DZone contributors are their own.

Related

  • Deep Dive Into Java Executor Framework
  • Configuring Spark-Submit
  • Apache Airflow Configuration and Tuning
  • Efficient Task Management: Building a Java-Based Task Executor Service for Your Admin Panel

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook