Lambda version of Print numbers alternately using two threads in Java

Lambda expressions in Java 8 are very powerful and therefore very compelling. Here are just a few of the key benefits to using lambda expressions in Java:

  • Conciseness
  • Reduction in code bloat
  • Readability
  • Elimination of shadow variables
  • Encouragement of functional programming
  • Code reuse
  • Enhanced iterative syntax
  • Simplified variable scope
  • Less boilerplate code
  • JAR file size reductions
  • Parallel processing opportunities

In this post, you can see how in few lines we can finish code to print numbers alternatively by Two threads.

import java.util.stream.IntStream;

public class EvenOddThreadLambdaDemo {

    static Integer number = new Integer(1);
    static Object LOCK = new Object();

    public static void main(String[] args) {


        IntStream.range(0, 1).forEach(i -> new Thread(() -> {
            printNumbers();
        }).start());
    }

    public static void printNumbers() {
        while (EvenOddThreadLambdaDemo.number < 20) {
            synchronized (LOCK) {
             // conditional naming of threads in case required in any usecase

                if (EvenOddThreadLambdaDemo.number %2 ==0) {
                    Thread.currentThread().setName("Even");
                }else{
                        Thread.currentThread().setName("Odd");
                }
                System.out.println(Thread.currentThread().getName() + "--> " + EvenOddThreadLambdaDemo.number++);
                LOCK.notify();
                try {
                    // let's not eat CPU if work is done.
                    LOCK.wait(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
/*
 Odd--> 1
 Even--> 2
 Odd--> 3
 Even--> 4
 Odd--> 5
 Even--> 6
 Odd--> 7
 Even--> 8
 Odd--> 9
 Even--> 10
 Odd--> 11
 Even--> 12
 Odd--> 13
 Even--> 14
 Odd--> 15
 Even--> 16
 Odd--> 17
 Even--> 18
 Odd--> 19
 Even--> 20
*/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s