Wednesday, September 17, 2014

Threads : Creating a thread in java using Runnable or Thread


To create a simple thread, we need to following steps:
  1.   Write a class and implements Runnable or extends Thread class.
  2.  Override run method. (This method is called when we start the thread).

If you extends Thread:
public class SimpleThread extends Thread {
       @Override
       public void run() {
              System.out.println("Simple Thread");
       }

       public static void main(String[] args) {
              new SimpleThread().start();
       }
}

Note: This is not a best practice as it will stop you to inherit other classes.

If you implements Runnable:
public class RunnableThread implements Runnable {

       @Override
       public void run() {
              System.out.println("Runnable Thread.");
       }

       public static void main(String[] args) {
              new Thread(new RunnableThread()).start();
       }
}
Note: Here, we pass the class instance to thread class and remaining things are same.
And it is best practice suggested by experts.


No comments:

Post a Comment