You are on page 1of 9

Before introducing the thread concept, we were unable to run more than one task in parallel.

It was a drawback, and to remove that drawback, Thread Concept was introduced.

A Thread is a very light-weighted process, or we can say the smallest part of the process that
allows a program to operate more efficiently by running multiple tasks simultaneously.

In order to perform complicated tasks in the background, we used the Thread concept in
Java. All the tasks are executed without affecting the main program. In a program or process,
all the threads have their own separate path for execution, so each thread of a process is
independent.

Another benefit of using thread is that if a thread gets an exception or an error at the time of
its execution, it doesn't affect the execution of the other threads. All the threads share a
common memory and have their own stack, local variables and program counter. When
multiple threads are executed in parallel at the same time, this process is known as
Multithreading.

In a simple way, a Thread is a:

 Feature through which we can perform multiple activities within a single process.
 Lightweight process.
 Series of executed statements.
 Nested sequence of method calls.

Thread Model

Just like a process, a thread exists in several states. These states are as follows:
1) New (Ready to run)

A thread is in New when it gets CPU time.

2) Running

A thread is in a Running state when it is under execution.

3) Suspended

A thread is in the Suspended state when it is temporarily inactive or under execution.

4) Blocked

A thread is in the Blocked state when it is waiting for resources.

5) Terminated

A thread comes in this state when at any given time, it halts its execution immediately.

Creating Thread

A thread is created either by "creating or implementing" the Runnable Interface or by


extending the Thread class. These are the only two ways through which we can create a
thread.

Let's dive into details of both these way of creating a thread:


Thread Class

A Thread class has several methods and constructors which allow us to perform various
operations on a thread. The Thread class extends the Object class. The Object class
implements the Runnable interface. The thread class has the following constructors that are
used to perform various operations.

 Thread()
 Thread(Runnable, String name)
 Thread(Runnable target)
 Thread(ThreadGroup group, Runnable target, String name)
 Thread(ThreadGroup group, Runnable target)
 Thread(ThreadGroup group, String name)
 Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() method)

The Runnable interface is required to be implemented by that class whose instances are
intended to be executed by a thread. The runnable interface gives us the run() method to
perform an action for the thread.

start() method

The method is used for starting a thread that we have newly created. It starts a new thread
with a new callstack. After executing the start() method, the thread changes the state from
New to Runnable. It executes the run() method when the thread gets the correct time to
execute it.

Let's take an example to understand how we can create a Java thread by extending the Thread
class:

public class ThreadExample1 extends Thread {

public void run()


{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{

ThreadExample1 t1 = new ThreadExample1();

t1.start();
}
}
Creating thread by implementing the runnable interface

In Java, we can also create a thread by implementing the runnable interface. The runnable
interface provides us both the run() method and the start() method.

Let's takes an example to understand how we can create, start and run the thread using the
runnable interface.

Lifecycle and States of a Thread in Java


A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant: 

1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated

The diagram shown below represents various states of a thread at any instant in time.
Life Cycle of a thread

1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state. When a thread lies in the new state, its code
is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
thread might actually be running or it might be ready to run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run. 
A multi-threaded program allocates a fixed amount of time to each individual thread. Each
and every thread runs for a short while and then pauses and relinquishes the CPU to another
thread so that other threads can get a chance to run. When this happens, all such threads
that are ready to run, waiting for the CPU and the currently running thread lie in a runnable
state.
3. Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the
following states: 
o Blocked
o Waiting

1. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is
received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed
waiting state.
2. Terminated State: A thread terminates because of either of the following reasons: 
o Because it exits normally. This happens when the code of the thread has been
entirely executed by the program.
o Because there occurred some unusual erroneous event, like segmentation fault or
an unhandled exception.
Implementing the Thread States in Java

In Java, to get the current state of the thread, use Thread.getState() method to get the current
state of the thread. Java provides java.lang.Thread.State class that defines the ENUM
constants for the state of a thread, as a summary of which is given below:

Example

class A extends Thread{

public void run(){

System.out.println("\t thread A started");

for(int i=0;i<=5;i++)

System.out.print("\t from thread A :"+i);

System.out.print("exit from thread A");

class B extends Thread{

public void run(){

System.out.println("\t thread B started");

for(int j=0;j<=5;j++)

System.out.println(" from thread B :"+j);

}
System.out.println("exit from thread B");

class C extends Thread{

public void run(){

System.out.println(" thread C started");

for(int k=0;k<5;k++)

System.out.println(" from thread C :"+k);

System.out.println("exit from thread C");

class Threadpriority{

public static void main(String args[]){

A t1=new A();

B t2=new B();

C t3=new C();

t3.setPriority(Thread.MAX_PRIORITY);

t2.setPriority(t1.getPriority()+1);

t1.setPriority(Thread.MIN_PRIORITY);

System.out.println("start of thread A");

t1.start();
System.out.println("start of thread B");

t2.start();

System.out.println("start of thread C");

t3.start();

Creation of thread by implementing Runnable


class x implements Runnable{
public void run(){
for(int i=0;i<10;i++)
{
System.out.println("\t Thread x :"+i);
}
System.out.println("end of thread x");
}
}
class y implements Runnable{
public void run(){
for(int j=0;j<10;j++)
{
System.out.println("\t Thread y :"+j);
}
System.out.println("end of thread y");
}
}
class runnabletest1{
public static void main(String args[]){

x t=new x();
Thread tx=new Thread(t);
tx.start();
y t1=new y();
Thread ty=new Thread(t1);
ty.start();
System.out.println("end of main thread");
}
}

You might also like