-
Notifications
You must be signed in to change notification settings - Fork 228
/
EvenAndOddPrinter.java
39 lines (30 loc) · 1.18 KB
/
EvenAndOddPrinter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.javatechie;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class EvenAndOddPrinter {
private static Object object = new Object();
private static IntPredicate evenCondition = e -> e % 2 == 0;
private static IntPredicate oddCondition = e -> e % 2 != 0;
public static void main(String[] args) throws InterruptedException {
CompletableFuture.runAsync(() -> EvenAndOddPrinter.printResults(oddCondition));
CompletableFuture.runAsync(() -> EvenAndOddPrinter.printResults(evenCondition));
Thread.sleep(1000);
}
public static void printResults(IntPredicate condition) {
IntStream.rangeClosed(1, 10)
.filter(condition)
.forEach(EvenAndOddPrinter::execute);
}
public static void execute(int i) {
synchronized (object) {
try {
System.out.println("Thread Name " + Thread.currentThread().getName() + " : " + i);
object.notify();
object.wait();
} catch (InterruptedException ex) {
//error log
}
}
}
}