Skip to content

Instantly share code, notes, and snippets.

@ak-git
Last active September 4, 2021 17:36
Show Gist options
  • Save ak-git/286d31902b310d611085e396d5f1d3ab to your computer and use it in GitHub Desktop.
Save ak-git/286d31902b310d611085e396d5f1d3ab to your computer and use it in GitHub Desktop.
A code snippet to print Even and Odd numbers using multi-threading
package com.ak.fx.core;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class ServiceTest {
@Test
void test() {
ExecutorService executorService = Executors.newFixedThreadPool(2);
IntStream.rangeClosed(1, 100).forEach(num -> {
CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
if ((x & 0x01) == 1) {
Logger.getAnonymousLogger().info("%d %s".formatted(x, Thread.currentThread().getName()));
}
return num;
}, executorService).join();
CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
if ((x & 0x01) != 1) {
Logger.getAnonymousLogger().info("%d %s".formatted(x, Thread.currentThread().getName()));
}
return num;
}, executorService).join();
});
executorService.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment