Friday, 1 August 2014

5 Different Coding Styles For Creating A Thread Including Lambda Expressions and Functional Interaces

What Is Thread ?

     Thread is a part of program that runs concurrently along with other parts. Threads make it possible for one part of the program to continue to do useful work while another part is blocked, waiting for some event to occur.

Java provides built-in support for Multithreaded Programming. Following are the different coding styles for creating a thread in Java.

1. Implementing Runnable Interface :

    The easiest way to create a thread is to create a class that implements Runnable Interface. To implement Runnable, you need to implement the abstract method run() in your Class.

public void run().

Inside run() method, you will define code that constitutes the new thread. After you create a Class that implements Runnable, you will instantiate an object of type Thread from within that class.

package com.speakingcs.threads;

public class RunnableThread implements Runnable{

    public static void main(String[] args) {
        Thread t;
 RunnableThread rt = new RunnableThread();
 t = new Thread(rt); // creating thread
 t.start(); // starting the thread

    }

     @Override
     public void run() {
 try {
     for(int i = 0; i < 10; i++) {
   System.out.println("Square of " + i + " is " + (i*i));
  Thread.sleep(500);
     }
 } catch(InterruptedException ie) {
     System.out.println("Thread is interrupted");
 }
  
     }

}

2. Extending Thread Class :

    The second way to create a thread is to create a new Class that extends "Thread " and then to create an instance of that class. The extended class must override the run() method, which is an entry point for new thread. It must also call start() to begin execution of new thread.

Here is the preceding program rewritten to extend Thread Class.

package com.speakingcs.threads;

public class ExtendThread extends Thread{

 
    public static void main(String[] args) {
  
 ExtendThread et = new ExtendThread();
 Thread t = new Thread(et);
 t.start();
    }
 
    public void run() {
 try {   
     for(int i = 0; i < 10; i++) {
         System.out.println("square of " + i + " is " + (i*i));
         Thread.sleep(500);
     }  
 } catch(InterruptedException ie) {
     System.out.println("Thread is interrupted");
 }
    }

}

3. Using Inner Classes :

    An Inner Class is a non-static nested class. It has access to all of the variables & methods of it's outer Class and may refer to them directly in the same way that other non-static members of outer Class do.

Here is the same program written using Inner Classes.

package com.speakingcs.threads;

public class InnerThread {

    public static void main(String[] args) {
  
      Runnable r = new Runnable() {

 @Override
 public void run() {    
       try {   
  for(int i = 0; i < 10; i++) {
      System.out.println("square of " + i + " is " + (i*i));
      Thread.sleep(500);
  }  
     } catch(InterruptedException ie) {
  System.out.println("Thread is interrupted");
     }
 }   
    };
    new Thread(r).start();
}

}

4. Using Anonymous Inner Classes :

    Anonymous Inner Class is one that is not assigned a name. Anonymous Inner Classes lets you write concise code and helps you to declare & instantiate a Class at the same time. Below is the above code written using Inner Classes.

package com.speakingcs.threads;

public class AnonymousThread {
 
     public static void main(String[] args) {
 new Thread( new Runnable() {
     @Override
     public void run() {
  try {   
      for(int i = 0; i < 10; i++) {
   System.out.println("square of " + i + " is " + (i*i));
   Thread.sleep(500);
      }  
  } catch(InterruptedException ie) {
      System.out.println("Thread is interrupted");
  }
     }   
 }).start();
    }

}

5. Using Lambda Expressions & Runnable Functional Interface :

    A Lambda Expression is, essentially an anonymous method. How ever, this method is not executed on its own. Instead, it is used to implement a method defined by Function Interface. Thus, a lambda expression results in a form of anonymous class. Lambda expression are also commonly referred to as closures.

A Function Interface is an interface that contains one and only one abstract method. The standard interface Runnable is a functional interface because it defines only one method: run().
 
package com.speakigcs.threads;

public class LambdaThread {
 
    public static void main(String[] args) {

 Runnable r = () -> {

      try {   
         for(int i = 0; i < 10; i++) {
    System.out.println("square of " + i + " is " + (i*i));
    Thread.sleep(500);
  }  
    } catch(InterruptedException ie) {
  System.out.println("Thread is interrupted");
  }
 };
  
 new Thread(r).start();
    }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.