Creating thread


Creating thread

Creation of threads can be done by using following two ways:

1) Extending the Thread class

A class is created that extends the java.lang.Thread class. This class overrides the run() method which is a part of the Thread class. Life of a thread begins inside run() method. An object of the new class can be created and start() method can be called to start the execution of a thread. Start() invokes the run() method on the Thread object.

2) Implementing the Runnable Interface

A new class is created which implements java.lang.Runnable interface and overrides run() method. A Thread object can be instantiated and call start() method on this object.

Example No.1:

Com.knowledge2life public class Main extends Thread { public static void main(String[] args) { Main thread = new Main(); thread.start(); System.out.println("Knowledge2life outside thread"); } public void run() { System.out.println("This code is running in a thread"); } }

OUTPUT:

Knowledge2life outside thread
This code is running in a thread

Example No.2:

Com.knowledge2life public class Main implements Runnable { public static void main(String[] args) { Main obj = new Main(); Thread thread = new Thread(obj); thread.start(); System.out.println("Knowledge2life outside of the thread"); } public void run() { System.out.println("This code is running in a thread"); } }

OUTPUT:

Knowledge2life outside of the thread
This code is running in a thread