0% found this document useful (0 votes)
19 views9 pages

Understanding Java Thread Concepts

The document discusses threads in Java. It defines a thread as the smallest unit of processing or a lightweight process that allows a program to perform multiple tasks simultaneously. Threads allow running tasks in the background without affecting the main program. Each thread has its own call stack and shares memory with other threads in the same process. The document then covers thread states, creating threads by extending the Thread class or implementing the Runnable interface, and provides examples of multithreading in Java.

Uploaded by

Cool Srik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views9 pages

Understanding Java Thread Concepts

The document discusses threads in Java. It defines a thread as the smallest unit of processing or a lightweight process that allows a program to perform multiple tasks simultaneously. Threads allow running tasks in the background without affecting the main program. Each thread has its own call stack and shares memory with other threads in the same process. The document then covers thread states, creating threads by extending the Thread class or implementing the Runnable interface, and provides examples of multithreading in Java.

Uploaded by

Cool Srik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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;
[Link]("Thread started running..");
[Link]("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{

ThreadExample1 t1 = new ThreadExample1();

[Link]();
}
}
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 [Link]() method to get the current
state of the thread. Java provides [Link] 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(){

[Link]("\t thread A started");

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

[Link]("\t from thread A :"+i);

[Link]("exit from thread A");

class B extends Thread{

public void run(){

[Link]("\t thread B started");

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

[Link](" from thread B :"+j);

}
[Link]("exit from thread B");

class C extends Thread{

public void run(){

[Link](" thread C started");

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

[Link](" from thread C :"+k);

[Link]("exit from thread C");

class Threadpriority{

public static void main(String args[]){

A t1=new A();

B t2=new B();

C t3=new C();

[Link](Thread.MAX_PRIORITY);

[Link]([Link]()+1);

[Link](Thread.MIN_PRIORITY);

[Link]("start of thread A");

[Link]();
[Link]("start of thread B");

[Link]();

[Link]("start of thread C");

[Link]();

Creation of thread by implementing Runnable


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

x t=new x();
Thread tx=new Thread(t);
[Link]();
y t1=new y();
Thread ty=new Thread(t1);
[Link]();
[Link]("end of main thread");
}
}

Common questions

Powered by AI

The Runnable interface provides flexibility by allowing a class to implement multiple interfaces, enhancing reusability and separation of tasks. Unlike extending the Thread class, which binds you to single inheritance from Thread, implementing Runnable allows the class to extend another superclass, thus integrating threading into existing hierarchies more seamlessly .

A Timed Waiting state occurs when a thread calls a method that includes a timeout parameter, like sleep or wait with a specified timeout. The thread remains in this state until the timeout expires or it receives a notification. In contrast, a Waiting state doesn't include a timeout and only transitions when explicitly notified by another thread .

In Java, threads can be created by extending the Thread class or by implementing the Runnable interface. The Thread class method involves extending the Thread directly and defining the run method, while the Runnable approach requires implementing Runnable and passing an instance to a Thread object, which then calls the start() method. Both methods require the run() method to define the thread’s actions .

Multithreading allows Java programs to perform multiple tasks simultaneously, utilizing CPU resources more effectively. It permits background operations without interrupting the main program flow, increases responsiveness, and maximizes the processor’s usage by executing multiple threads concurrently, leading to better resource utilization and program efficiency .

Exception handling in threads ensures that a malfunction in one thread doesn’t halt the execution of other threads in a program. If a thread encounters an error, it doesn’t impede the activities in other threads due to the isolated execution paths and separate stack each maintains, enabling other threads to continue executing .

Shared memory in Java threads means all threads have access to the same data space, enabling easy communication and data exchange. However, this requires careful synchronization to avoid race conditions and ensure data consistency, complicating development but potentially improving performance by reducing data duplication .

Java threads run tasks simultaneously by each having their own stack, local variables, and program counter. They share a common memory space, but the independent execution paths of each thread ensure that if one encounters an exception, it doesn’t impact the others. This allows tasks to execute concurrently without affecting each other .

Thread priority in Java determines the relative importance of threads. The JVM uses these priorities to decide thread scheduling, although this is dependent on the underlying operating system’s scheduling mechanism. High priority threads usually get preference over lower priority threads, hence they are more likely to run sooner if they are ready to execute .

The 'start()' method is critical as it initiates a new thread, changing its state from New to Runnable and creating a new call stack for the thread. Once 'start()' is invoked, the thread becomes eligible for execution by the thread scheduler, which eventually enables the run() method to execute at the right time .

A thread begins in the New state, moving to the Runnable state when it is ready to run. The thread scheduler determines when a thread actually runs. In multi-threaded programs, threads receive a fixed amount of execution time before yielding to another thread. A thread becomes Blocked or in Waiting state when it’s inactive, possibly awaiting resources or conditions, and transitions to Timed Waiting if given a timeout. Finally, the thread reaches the Terminated state when its code has either completed normally or due to an unhandled error .

You might also like