Threads allow a program to do multiple things at the same time.
New: The thread is in a new state when you create an instance of the thread class. It remains in this state before the start()
method is invoked.
Runnable: The thread is in a runnable state after the invocation of the start()
method, but the thread is not scheduled by the scheduler.
Running: The thread is put in a running state once the thread scheduler selects it.
Non Runnable: In this state the thread is alive, but not running.
Terminated: A thread is in a terminated or dead state when it’s run()
method exits.
There are two methods for creating threads:
Using Thread class
Using Runnable Interface
Thread
Classi) Create a thread class:
public class Myclass extends Thread
ii) Override therun()
method:
public void run();
iii) Create an object of the class:
MyThread obj = new MyThread();
iv) Invoke the start()
method:
obj.start();
class MyThread extends Thread{public void run(){System.out.println("Thread is running...");}public static void main(String args[]){MyThread obj = new MyThread();obj.start();}}
i) Create a thread class:
public class MyThread implements Runnable
ii) Override the run()
method:
public void run();
Note: We can also use
@override
to overriderun()
.
iii) Create an object of the class:
Thread t = new Thread(new MyThread());
Note: we use
new
twice because theMyThread
class does not extend the thread class. We can also write the same thing as:
Runnable r = new MyThread();
Thread t = new Thread(r);
iv)Inoke start() method:
t.start();
Note: We use runnable interface because if a class is already a child of its parent class, it cannot extend the thread class. Hence, it can implement runnable interface.
class MyThread implements Runnable{public void run(){System.out.println("Thread is running...");}public static void main(String args[]){MyThread r = new MyThread();Thread t =new Thread(r);t.start();}}
run()
method