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

Unit4 Multi Threading

Multi-threading is a programming paradigm that allows concurrent execution of multiple threads, improving resource utilization and enabling complex problem-solving. Java supports multi-threading through the Thread class and the Runnable interface, allowing developers to create and manage threads easily. The document also covers thread lifecycle, scheduling, methods for managing threads, and the importance of thread priorities in execution order.

Uploaded by

bunevu654
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 views71 pages

Unit4 Multi Threading

Multi-threading is a programming paradigm that allows concurrent execution of multiple threads, improving resource utilization and enabling complex problem-solving. Java supports multi-threading through the Thread class and the Runnable interface, allowing developers to create and manage threads easily. The document also covers thread lifecycle, scheduling, methods for managing threads, and the importance of thread priorities in execution order.

Uploaded by

bunevu654
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

Multi-threading

• Multi-threading programming is a conceptual paradigm where one


can divide a program into two or more processes which can be run in
parallel.
• There are two main advantages of multi-threading: First, program
with multiple threads will, in general, result in better utilization of
system resources, including the CPU, because another line of
execution can grab the CPU when one line of execution is blocked.
• Second, there are several problems better solved by multiple threads.
• For example, we can easily write a multi-threaded program to show
animation, play music, display documents, and download files from
the network at the same time.
18-11-2025 1
Multi-threading
• Java is a multi-threaded language.
• Java allows to write a program where more than one processes can be
executed concurrently within the single program.
• Java's threads are often referred to as light weight threads, which
means that they run in the same memory space.
• Because Java threads run in the same memory space, they can easily
communicate among themselves because an object in one thread can
call a method in another thread without any overhead from the
operating system.

18-11-2025 2
Basics of a Thread
• Everything about thread are defined in a class Thread.
• The Thread class encapsulates all of the control one will need over
threads.
• The Thread class is our only link to manage how threads behave.
Creating and Running a Thread
• There are two ways to define a thread:
1. By extending Thread class
2. By implementing Runnable interface

18-11-2025 3
Basics of a Thread
Using the sub classing thread:
• With this method, we have to define a class as a sub class of the
Thread class.
• This sub class should contain a body which will be defined by a
method run().
• This run() method contains the actual task that the thread should
perform.
• An instance of this sub class is then to be created by a new statement,
followed by a call to the thread's start() method to have the run()
method executed.

18-11-2025 4
Thread Scheduler
• Responsible to schedule threads.
• It is part of JVM.
• It varies from system to system.
• If multiple threads are waiting to get chance of execution then in
which order thread will be executed, is decided by Thread Scheduler.
• Hence output order may vary for each execution.
Creating and running threads using sub
classing Thread
Creating and running threads using sub
classing Thread
• In this example,
three threads will
be executed
concurrently.
• A thread can be
directed to start
its body by start()
method.
Creating and running threads using sub
classing Thread
Difference b/w [Link]() & [Link]()
[Link]() 🡪 Execution order is not fixed.
Here new Thread will be created that is responsible for execution of
run() method.

[Link]() 🡪 Execution order is fixed.


A new thread won’t be created and run() method will be executed
as normal method call by main thread.
Using the Runnable interface
• A second way to create threads is to make use of the Runnable interface.
• With this approach, first we have to implement the Runnable interface.
• Runnable interface is already defined in the system package [Link] with a
single method run() as below :
public interface Runnable {
public abstract void run( );
}
• When we create a new thread, actually a new object will be instantiated from this
Runnable interface as the target of our thread, meaning that the thread will look
for the code for the run( ) method within our object's class instead of inside the
Thread's class.
Creating three threads using the Runnable
interface and then running them concurrently
Creating three threads using the Runnable
interface and then running them concurrently

This is not a thread, it’s just a normal object containing run().


This wraps the Runnable object into a real thread.

x is NOT a thread. It is only a Runnable job.


new Thread(x) creates the real thread that will run the job.
Creating three threads using the Runnable
interface and then running them concurrently
Methods Defined in Thread Class
• public static Thread currentThread();
Returns: the currently executing thread

• public static int enumerate( Thread[] tarray); tarray - an array into


which to put the list of threads
Returns: the number of threads put into the array
• public final String getName();
Returns: this thread's name
• public final int getPriority();
Returns: this thread's priority
• public final ThreadGroup getThreadGroup();
Returns: this thread's thread group
• public void interrupt();
used to interrupt a sleeping or waiting thread
Throws: SecurityException - if the current thread cannot modify this thread
• public static boolean interrupted();
Returns: true if the current thread has been
interrupted; false otherwise

• public final boolean isDaemon();


Returns: true if this thread is a daemon thread; false
otherwise

• public final void join();


Throws: InterruptedException - if any thread has
interrupted the current thread. The interrupted status of
the current thread is cleared when this exception is
thrown
public final void join(long ms);
public final void join(long ms , long ns);
🡪 Every join() method throws
InterruptedException that is checked exception
Hence compulsory to handle this exception
• public void run();
Entry point for the thread.
Description: If this thread was constructed using a
separate Runnable run object, then that Runnable
object's run method is called; otherwise, this method
does nothing and returns. Subclasses of Thread should
override this method.
• public static void yield();
Description: A hint to the scheduler that the
current thread is willing to yield its current use of a
processor. The scheduler is free to ignore this hint

• public void start();


Start a thread by calling run() method
Throws: IllegalThreadStateException - if the thread
was already started.
• public static void sleep(long ms);
• public static void sleep(long ms, int ns);

Parameters: ms - the length of time to sleep in


milliseconds
ns- nano seconds

Throws: IllegalArgumentException - if the value of


millis is negative InterruptedException - if any thread
has interrupted the current thread. The interrupted
status of the current thread is cleared when this
exception is thrown.
• public final void setPriority(int newPriority);
Parameters: newPriority - priority to set this thread
to.. Its range is from 1 to 10
Throws: IllegalArgumentException- If the priority is
not in the range MIN_PRIORITY to MAX_PRIORITY
SecurityException - if the current thread cannot modify
this thread.
• public final void setName(String name);
Parameters: name - the new name for this thread.
Throws: SecurityException - if the current thread
cannot modify this thread.
Inside a start() method
start(){
1. Register this thread with Thread Scheduler
2. Perform all the other mandatory activity
3. Invoke run() method
}
More about run() method
Overloading of run() method is always possible but the start()
method of thread class can invoke no argument run() method

The other overloaded methods we have to call explicitly like a


normal method call
E.g. 1🡪 class Mythread extends Thread{
public void run(){
[Link](“no argument method”);
}
public void run(int x){
[Link](“argument method”);
}
}
class ThreadDemo{
public static void main(String args[]){
Mythread t=new Mythread();
[Link]();
}
}
Output: no argument method
E.g. 2🡪
class Mythread extends Thread{
}
class ThreadDemo{
public static void main(String args[]){
MyThread t=new MyThread();
[Link]();
}
}
Output: 🡪we won’t get any output because Thread
class run() method has empty implementation
Overriding start() method
E.g. 1🡪 class Mythread extends Thread{
public void start(){
[Link](“start method”);
} start() → creates a new thread → calls run() in that new thread
public void run(){
[Link](“run method”);
}
}
class ThreadDemo{
public static void main(String args[]){
MyThread t=new MyThread();
[Link]();
[Link](“main method”);
}
}
Output: start method
main method
E.g. 2🡪 class Mythread extends Thread{
public void start(){
[Link](); starts a new thread
[Link](“start method”);
} The rest of start() continues in main thread Because threads run
public void run(){ independently, the order of main method and run method is not fixed
[Link](“run method”);
}
}
class ThreadDemo{
public static void main(String args[]){
Mythread t=new Mythread();
[Link]();
[Link](“main method”);
}
}
Output: start method main method run method
main method run method start method
run method start method main method
Some important points
🡪 When a thread is started once it can’t be restarted
again. If we will try to restart then exception will be
raised saying…
…IllegalThreadStateException
It’s an run time exception
public static void main(String args[])
{
Thread t=new Thread();
[Link]();
[Link]();//Here exception will be raised
}
🡪 We can define a thread by implementing Runnable
interface
Runnable interface doesn’t contain start() method. It
contains only run() method.
--------------------------------------------
class MyRunnable implements Runnable{
public void run(){
for( int i=0;i<10;i++)
[Link](“Child Thread”);
}
}

Job of the thread


🡪Executed by
child thread
class ThreadDemo{
public static void main(String args[]){
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);
[Link]();
for(int i=0;i<10;i++)
[Link](“main thread”);
}
}
Output: we will get mixed output …means n number of
outputs are possible
class ThreadDemo{
public static void main(String args[]){
MyRunnable r=new MyRunnable();
Thread t1=new Thread();
Thread t2=new Thread(r);
}
}
Case study
----------------------------
1. [Link]();
A new thread will be created and which is
responsible for execution of thread class run() method
which has empty implementation
2. [Link]();
no new thread will be created and thread class run()
method will be executed just like normal method call.
3. [Link]();
A new thread will be created which is responsible
for execution of MyRunnable run() method.
4. [Link]();
no new thread will be created and MyRunnable
run() method will be executed just like normal method
call.
5. [Link]();
We will get compile time error because Runnable
interface doesn’t have start() method
6. [Link]();
MyRunnable run() method will be executed like
normal method call and no new thread will be created.

🡪 We should define a thread by implementing


Runnable interface because by this way we won’t miss
inheritance property.
Constructors of Thread class
1. Thread t=new Thread();
2. Thread t=new Thread(Runnable r);
3. Thread t=new Thread(String name);
4. Thread t=new Thread(Runnable r, String name);
5. Thread t=new Thread( ThreadGroup g, String
name);
6. Thread t=new Thread( ThreadGroup g, Runnable r);
7. Thread t=new Thread( ThreadGroup g, Runnable r,
String name);
8. Thread t=new Thread( ThreadGroup g, Runnable r,
String name, long stack_size);
Extra 🡪 Thread t=new Thread(Thread r);
Life cycle of threads
Life cycle of threads
• Each thread is always in one of five states.
• Newborn: When a thread is created (by new statement) but not yet to run, it is called in
Newborn state. In this state, the local data members are allocated and initialized.
• Runnable: The Runnable state means that a thread is ready to run and is awaiting for the
control of the processor, or in other words, threads are in this state in a queue and wait
their turns to be executed.
• Running: Running means that the thread has control of the processor, its code is currently
being executed and thread will continue in this state until it get preempted by a higher
priority thread, or until it relinquishes control.
• Blocked: A thread is Blocked means that it is being prevented from the Runnable (or
Running) state and is waiting for some event in order for it to reenter the scheduling
queue.
• Dead: A thread is Dead when it finishes its execution or is stopped (killed) by another
thread.
• Threads move from one state to another via a variety of means.
• The common methods for controlling a thread's state is shown in Figure.

start ( ) : A newborn thread with this method enter into Runnable state and Java run time create a system
thread context and starts it running. This method for a thread object can be called once only

stop( ) : This method causes a thread to stop immediately. This is often an abrupt way to end a thread.
suspend( ) : This method is different from stop( ) method. It takes the thread and causes it to stop running and
later on can be restored by calling it again.

resume ( ) : This method is used to revive a suspended thread. There is no guarantee that the thread will start
running right way, since there might be a higher priority thread running already, but, resume()causes the thread
to become eligible for running.

sleep (int n ) : This method causes the run time to put the current thread to sleep for n milliseconds. After n
milliseconds have expired, this thread will become eligible to run again.

yield( ) : The yield() method causes the run time to switch the context from the current thread to the next
available runnable thread. This is one way to ensure that the threads at lower priority do not get started.
Create a new thread and execute its run() method in that new thread.
In multithreading, each time the output is different because thread scheduling is unpredictable.
18-11-2025 40
When i == 1, the thread voluntarily gives
up the CPU.
The scheduler may allow other threads
(ClassB, ClassC, or main) to run.
yield() does not stop the thread; it only
suggests the scheduler to switch.

volatile ensures visibility across threads.

18-11-2025 41
18-11-2025 42
Because threads run concurrently,
and the OS scheduler decides the
order.
yield() → hints to pause
sleep() → forces pause Safe stop
flag → stops thread B early
But all three threads + main run
independently.

18-11-2025 43
Thread Priorities
• Every thread in java has some priority either provided by programmer
or JVM.
• Priority range is 1 to 10.
• Thread Scheduler will use priorities while allocating processor.
• Thread with highest priority will get chance first to execute
• If priorities are same then we can’t expect that which thread will get
chance first.
• The default priority for main thread is 5 but for all
remaining threads default priority will be inherited
from parent thread to child thread.
• These are the methods to get and set priority of a
thread
🡪 public final int getPriority();
🡪 public final void setPriority(int p);
• Some predefined constants for priority
1. Thread.MIN_PRIORITY for 1
2. Thread.MAX_PRIORITY for 10
3. Thread.NORM_PRIORITY for 5
Sample program for Priority Demo
public static void main(String args[]){
[Link](“current thread priority:”+
[Link]().getPriority());// 5
[Link]().setPriority(12); //runtime
exception
[Link]().setPriority(7);
MyThread t=new MyThread();
[Link]();
[Link](“current thread priority:”+
[Link]());// 7
}
}
Example on Priority
class Mythread extends Thread{
public void run(){
for( int i=0;i<10;i++){
[Link](“Child Thread”);
}
}
}
class ThreadPriorityDemo{
public static void main(String args[]){
MyThread t=new MyThread();
[Link](10);
[Link]();
for( int i=0;i<10;i++)
[Link](“Parent Thread”);
}
}
Output: It will display Child Thread and Parent Thread in any order
Note:
In the previous program at some system output may
vary for each execution because some systems don’t
follow priority order
Marks thread as “suspended".

18-11-2025 49
18-11-2025 50
Status of a Thread
• It is some time essential to know some information about threads. There are number of methods defined in
Thread which can be called for getting information about threads. Some of the most commonly used methods
for thread's status are listed here :
• currentThread( ) : The CurrentThread() is a static method returns the Thread object which is the currently
running thread.
• setName( String s) : The SetName() method is to assign a name s for a thread prior its execution. This,
therefore, identifies the thread with a string name. This is helpful for debugging multi-threaded programs.
• getName( ) : This method returns the current string value of the thread's name as set by SetName().
• setPriority (int p) : This method sets the thread's priotity to an integer value p passed in. There are several
predefined priotiry constants defined in class Thread : MIN-PRIORITY, NORM-PRIORTY and
MAX-PRIORITY, which are 1, 5, and 10 respectively.
• getPriority ( ) : This method returns the thread's current priority, a value between 1 and 10.
• isAlive ( ) : This method returns true if the thread is started but not dead yet.
• isDaemon ( ) : This method returns true if the thread is a daemon thread.

18-11-2025 51
Setting priority to Threads

18-11-2025 52
Setting priority to Threads

18-11-2025 53
Data Race Example

18-11-2025 54
1. x is a static shared variable

All threads modify the same x.

2. Each thread performs:

x = x + 1;

x = x - 1;

This should keep x unchanged.

3. These operations are NOT atomic

Each one actually has 3 steps:

Load

Modify

Store

Threads can interrupt each other during these steps.

4. This causes a race condition

Multiple threads reading and writing x at the same time → unpredictable results.

5. The main thread prints x immediately

It does NOT wait for worker threads → prints x while other threads are modifying it.

6. Therefore, printed values are NOT always 0

Because updates are interleaving from different threads.

7. To fix this:

Use synchronized, OR

Use AtomicInteger, OR

Use join() to wait for threads to finish.

18-11-2025 55
Preventing Thread execution temporarily
• Methods
1. yield();
2. join();
3. sleep();
1. yield() method
• This method causes to pause the current executing thread to give the
chance to other waiting thread of same priority. If there is no waiting
thread or all the waiting threads having low priority then same thread
can continue its execution.
• If multiple threads are waiting with same priority then which thread
will get chance , it depends on thread scheduler
• The thread which is yielded ,when again it will get chance
,it depends on thread scheduler
public static native void yield();
Sample program
-----------------
Class MyThread extends Thread{
public void run(){
for(int i=0;i<10;i++){
[Link](“child thread”);
[Link]();
}
} Line 1
}
class ThreadYieldDemo{
public static void main(String args[]){
MyThread t=new MyThread();
[Link]();
for(int i=0;i<10;i++){
[Link](“parent thread”);
}
}
}
In this program if we comment Line 1 then the both threads
will be executed simultaneously and we can’t expect that
which thread will complete its execution first else child
thread always calls yield() method so main thread will get
more chance .Hence chance of completion of main thread
is more than child thread
Impact of yield() method on life cycle of a
Thread
MyThread t=new MyThread(); [Link]();

New / [Link]();
Born Ready/
Running
Runnable
If Thread

If run d
meth etes
comp
Scheduler
allocate

()
o
l
processors

Dead
2. join() method
• If thread wants to wait until completing some other
thread then we can go for join() method. For example
a thread t1 wants to wait until completing the
execution of thread t2 then t1 has to call [Link]();
🡪eg.

Venue fixing Wedding card Wedding card


activity(t1) printing(t2) distribution(t3)
t2 t2
t1

[Link](); [Link]();
In the above example t2 has to wait until venue
fixing thread t1 completion, hence t2 has to call
[Link]() method.
Wedding card distribution thread t3 has to wait until
completion of wedding card printing, hence t3 has to
call [Link]() method.
public final join();
public final join(long ms );
public final join(long ms , int ns);
🡪An example for join() method
class MyThread extends Thread{
public void run(){
for( int i=0;i<10;i++){
[Link](“child thread”);
try{
[Link](1000);
}
catch(InterruptedException e){}
}
}
}
class ThreadJoinDemo {
public static void main(String args[]){
MyThread t=new MyThread();
[Link]();
[Link]();
//[Link](2000); Line 1
//[Link](2000,80);
for(int i=0;i<10;i++)
[Link](“child thread”);
}
}
//here main thread will wait until completion of child
thread
🡪 If we comment Line 1 then both main and child
thread will be executed simultaneously and we can’t
except exact output.

🡪 If we don’t comment Line 1 then main thread


calls join() on child thread ,hence main thread will wait
until completion of child thread
Impact of join() method on life cycle of a
Thread
MyThread t=new MyThread(); If Thread
Scheduler allocate
New / processors
[Link]();
Born Ready/
Running
Runnable

If run d
meth etes
comp
o r
l ete s
r upted
p
om ires or ot inter

()
o
2 c

l
If t e exp ead g ; 00); 00);
t i m t h r ( )
If i t ing o in (10 0,1
a . j
If w t2 .join (200
Waiting state T2 .join
T2 Dead
(Blocked for joining)
3. sleep() method
• If a thread don’t want to perform any operation for a
particular amount of time then sleep() method is useful
.
🡪 public static native void sleep (long ms);
🡪 public static void sleep(long ms ,int ns);
• Every sleep() method throws InterruptedException
which is checked exception , handling is compulsory.

Those methods which are


not implemented in java
🡪 An example for sleep() method
class SlideRotator{
public static void main(String args[]) throws
InterruptedException{
for(int i=1;i<=10;i++){
[Link](“slide_”+i);
[Link](2000);
}
}
}
How a thread can interrupt another thread!
• A thread can interrupt a sleeping or waiting thread by using interrupt() method of Thread class
🡪 public void interrupt();
An example
-----------------------------
class MyThread extends Thread{
public void run(){
try{
for(int i=0;i<0;i++){
[Link](“I am lazy”);
[Link](1000);
}
}
catch(InterruptedException e){
[Link](“I got Interrupted”);
}
}
}
class ThreadInterruptDemo{
public static void main(String args[]){
MyThread t=new MyThread();
[Link](); Line 1
[Link]();
[Link](“End of main thread”);
}
}
🡪 If we comment Line 1 then main thread will not interrupt
child thread. Hence child thread will execute 10 times else
child thread will not execute 10 times.
• When ever we are calling interrupt() method if the target
thread is not sleeping or waiting then there is no impact
of interrupt() call immediately.

You might also like