Advertisement
javatechie

Even and Odd using CompletableFuture

Aug 18th, 2020
1,930
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. package com.javatechie.multithreading;
  2.  
  3. import java.util.concurrent.CompletableFuture;
  4. import java.util.function.IntPredicate;
  5. import java.util.stream.IntStream;
  6.  
  7. public class EvenOddThreadCommunication {
  8.  
  9.     private static Object object = new Object();
  10.     private static IntPredicate evenCondition = e -> e % 2 == 0;
  11.     private static IntPredicate oddCondition = e -> e % 2 != 0;
  12.  
  13.     public static void main(String[] args) throws InterruptedException {
  14.         CompletableFuture.runAsync(() -> EvenOddThreadCommunication.print(oddCondition));
  15.         CompletableFuture.runAsync(() -> EvenOddThreadCommunication.print(evenCondition));
  16.         Thread.currentThread().sleep(1000);
  17.     }
  18.  
  19.     public static void print(IntPredicate condition) {
  20.         IntStream.range(1, 11).filter(condition).forEach(EvenOddThreadCommunication::execute);
  21.     }
  22.  
  23.  
  24.     public static void execute(int i) {
  25.         synchronized (object) {
  26.             try {
  27.                 System.out.println(Thread.currentThread().getName() + " : " + i);
  28.                 object.notify();
  29.                 object.wait();
  30.             } catch (InterruptedException e) {
  31.                 e.printStackTrace();
  32.             }
  33.         }
  34.     }
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement