Last active
September 4, 2021 17:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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