0% found this document useful (0 votes)
5 views8 pages

Thread Notes

A Java thread is a lightweight process that allows for concurrent execution within a multithreaded program, which is a specialized form of multitasking. Java supports two methods for creating threads: by extending the Thread class or implementing the Runnable interface, and threads go through various states such as new, runnable, running, blocked, and dead. Synchronization is essential in Java to ensure that shared resources are accessed by only one thread at a time, preventing data inconsistency.

Uploaded by

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

Thread Notes

A Java thread is a lightweight process that allows for concurrent execution within a multithreaded program, which is a specialized form of multitasking. Java supports two methods for creating threads: by extending the Thread class or implementing the Runnable interface, and threads go through various states such as new, runnable, running, blocked, and dead. Synchronization is essential in Java to ensure that shared resources are accessed by only one thread at a time, preventing data inconsistency.

Uploaded by

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

What is a Java Thread?

A thread is actually a lightweight process. Unlike many other computer languages,


Java provides built-in support for multithreaded programming. A multithreaded
program contains two or more parts that can run concurrently. Each part of such a
program is called thread and each thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking.

In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern
operating systems support multitasking. There are two types of multitasking, and they
are as follows.

• Process-based multitasking
• Thread-based multitasking

It is important to know the difference between process-based and thread-based


multitasking. Let's distinguish both.

Process-based multitasking Thread-based multitasking

It allows the computer to run two or more It allows the computer to run two or more
programs concurrently threads concurrently

In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires seperate address space for Threads share same address space.
each.

Process never gain access over idle time of Thread gain access over idle time of CPU.
CPU.

Inter process communication is expensive. Inter thread communication is not


expensive.
In java, a thread goes through different states throughout its execution. These stages are
called thread life cycle states or phases. A thread may in any of the states like new, ready or
runnable, running, blocked or wait, and dead or terminated state. The life cycle of a thread in
java is shown in the following figure.

New
When a thread object is created using new, then the thread is said to be in the New
state. This state is also known as Born state.

Example
Thread t1 = new Thread();

Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state.
This state is also known as a Ready state.

Example
[Link]( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( )
method of a thread called automatically by the start( ) method.

Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons
like sleep( ) method called, wait( ) method called, suspend( ) method called, and join(
) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due
to reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( )
method called, resume( ) method called, etc.

Example
[Link](1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();

Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated
state.

The java programming language provides two methods to create


threads, and they are listed below.

• Using Thread class (by extending Thread class)


• Uisng Runnable interface (by implementing Runnable interface)

• Extending Thread class


• The java contains a built-in class Thread inside the [Link] package. The
Thread class contains all the methods that are related to the threads.
Example
class SampleThread extends Thread{

public void run() {


[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++) {
[Link]("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
[Link]("Thread about to start...");
[Link]();
}
}

Implementng Runnable interface


The java contains a built-in interface Runnable inside the [Link] package. The
Runnable interface implemented by the Thread class that contains all the methods
that are related to the threads.

Example
class SampleThread implements Runnable{

public void run() {


[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++) {
[Link]("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
[Link]("Thread about to start...");
[Link]();
}
}

The Thread class defines several methods that help manage [Link] table below
displays the same:

Method Meaning
getName Obtain thread’s name
getPriority Obtain thread’s priority
isAlive Determine if a thread is still running
join Wait for a thread to terminate
run Entry point for the thread
sleep Suspend a thread for a period of time
start Start a thread by calling its run method

Java Thread Priority


n a java programming language, every thread has a property called priority. Most of
the scheduling algorithms use the thread priority to schedule the execution sequence.
In java, the thread priority range from 1 to 10. Priority 1 is considered as the lowest
priority, and priority 10 is considered as the highest priority. The thread with more
priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority,
and they are listed below.

• MAX_PRIORITY - It has the value 10 and indicates highest priority.


• NORM_PRIORITY - It has the value 5 and indicates normal priority.
• MIN_PRIORITY - It has the value 1 and indicates lowest priority.

🔔 The default priority of any thread is 5 (i.e. NORM_PRIORITY).


setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes
an integer range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.

Example

[Link](4);
or
[Link](MAX_PRIORITY);

getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It
does not takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.

Example

String threadName = [Link]();

Look at the following example program.

Example

class SampleThread extends Thread{


public void run() {
[Link]("Inside SampleThread");
[Link]("Current Thread: " +
[Link]().getName());
}
}

public class My_Thread_Test {


public static void main(String[] args) {
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
[Link]("first");
[Link]("second");

[Link](4);
[Link](Thread.MAX_PRIORITY);

[Link]();
[Link]();

}
}

Java Synchronization
At times when more than one thread try to access a shared resource, we need to
ensure that resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization. The synchronization keyword in java
creates a block of code referred to as critical section.
General Syntax:
synchronized (object)
{
//statement to be synchronized
}
Every Java object with a critical section of code gets a lock associated with the
object. To enter critical section a thread need to obtain the corresponding object's
lock.

Why we need Syncronization?


If we do not use syncronization, and let two or more threads access a shared
resource at the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts
execution and save certain values in a file [Link] which will be used to
calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns,
T2 change the values saved by T1 in the file [Link] ([Link] is the
shared resource). Now obviously T1 will return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in
above case, once T1 starts using [Link] file, this file will be locked(LOCK
mode), and no other thread will be able to access or modify it until T1 returns.

You might also like