Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javatechie.multithreading;
- import java.util.concurrent.CompletableFuture;
- import java.util.function.IntPredicate;
- import java.util.stream.IntStream;
- public class EvenOddThreadCommunication {
- 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(() -> EvenOddThreadCommunication.print(oddCondition));
- CompletableFuture.runAsync(() -> EvenOddThreadCommunication.print(evenCondition));
- Thread.currentThread().sleep(1000);
- }
- public static void print(IntPredicate condition) {
- IntStream.range(1, 11).filter(condition).forEach(EvenOddThreadCommunication::execute);
- }
- public static void execute(int i) {
- synchronized (object) {
- try {
- System.out.println(Thread.currentThread().getName() + " : " + i);
- object.notify();
- object.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement