Java 8 Threading Using Lambda expression Example

As we already know that In Java, we can create thread using two ways - using extends and another is using Runnable.

Normally we create Thread using below ways.
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Threading Using old way !");
}
});
t1.start();

We write codes because we are interested in doing something. we write something and expecting some output. We are more interested in outcome that our code is supposed to provide. here we expect our code to print "Threading Using old way!" once it runs.
But It seems we are writing extra codes for simple thing !



Using Java 8 Lambda Expression, we don't need to write lots of line for single thing.

Thread t2 = new Thread(() -> System.out.println("Threading using lambda!"));
t2.start();

Output
Threading Using old way !
Threading using lambda!

No comments:

Post a Comment