0% found this document useful (0 votes)
5 views

10 Multithreading

The document outlines the curriculum for a Java Programming course focusing on multithreading. It covers various topics including execution techniques, benefits of multithreading, thread lifecycle, and methods for creating threads in Java. Key concepts such as thread states, thread priority, and the differences between extending the Thread class and implementing the Runnable interface are also discussed.

Uploaded by

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

10 Multithreading

The document outlines the curriculum for a Java Programming course focusing on multithreading. It covers various topics including execution techniques, benefits of multithreading, thread lifecycle, and methods for creating threads in Java. Key concepts such as thread states, thread priority, and the differences between extending the Thread class and implementing the Runnable interface are also discussed.

Uploaded by

okokji4201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

School of Computer Science and Engineering

Course Code: E1UA307C Course Name: Java Programming

DEPARTMENT OF COMPUTER SCIENCE


& ENGINEERING
Subject Name: Java Programming
Topics Covered: Multithreading

1
Faculty Name: Programe Name: B.Tech
List of Topics to be covered
 Different types of Execution Techniques
 Thread
 Multithreading
 Different types of multitasking thread-based and
process-based multitasking
 Benefits of Multithreading
 Life Cycle of Thread
 Multithreaded Server: For Serving Multiple Clients
Concurrently
 Creating threads in Java
2
Different types of Execution Techniques
Multitasking: Ability to execute more than one task at the same
time is known as multitasking.

Multithreading: It is a process of executing multiple threads


simultaneously. Multithreading is also known as Thread-based
Multitasking.

Multiprocessing: It is same as multitasking, however in


multiprocessing more than one CPUs are involved. On the other hand
one CPU is involved in multitasking.
3
Multitasking and the Types of Multitasking
Multitasking is an approach to minimize execution time and
maximize CPU utilization by executing multiple tasks
simultaneously. You can achieve the process of multitasking in
Java using two methods, as described below.

4
Multiprocessing in Java
Multiprocessing in Java is purely based on the number of processors available
on the host computer. Every process initiated by the user is sent to the CPU
(processor). It loads the registers on the CPU with the data related to the
assigned process.

To perform multiprocessing in Java, the user needs one processor. Therefore,
when the user requests the simultaneous execution of the second process, the
alternate CPU core gets triggered and executes the process.

5
Multithreading in Java
Multithreading in Java is a similar approach to multiprocessing. However,
there are some fundamental differences between the two. Instead of a
physical processor, multithreading involves virtual and independent
threads.

It assigns each process with one or more threads based on their
complexity. Each thread is virtual and independent of the other. This
makes process execution much safer. If a thread or two are terminated
during an unexpected situation, the process execution will not halt.

6
Thread
Thread: single sequential flow of control within a program

Single-threaded program can handle one task at any time.

Multitasking allows single processor to run several concurrent


threads.

Most modern operating systems support multitasking.

7
Benefits of Multithreading
Enables programmers to do multiple things at one time
Programmers can divide a long program into threads and execute
them in parallel which eventually increases the speed of the program
execution
 Improved performance and concurrency
 Simultaneous access to multiple applications
Different processes do not share memory space.
A thread can execute concurrently with other threads within a
single process.
All threads managed by the JVM share memory space and can
communicate with each other.
8
Way of Execution of multiple Threads
Threads Concept
Thread 1
Thread 2

Multiple threads Thread 3

on multiple CPUs

Multiple Thread 1
Thread 2
Thread 3

threads
sharing a
single CPU

9
Lifecycle of a Thread
in Java

The lifecycle of each


thread in Java has five
different stages. You
will look into each one
of those stages in
detail. The Stages of
the Lifecycle are
mentioned below.
New
Runnable
Running
Waiting
Dead
10
A thread keeps running until the following conditions occurs

Thread give up its control on its own and it can happen in the following situations

 A thread gets suspended using suspend() method which can only be revived
with resume() method

 A thread is made to sleep for a specified period of time using sleep(time)


method, where time in milliseconds

 A thread is made to wait for some event to occur using wait () method. In this
case a thread can be scheduled to run again using notify () method.

 A thread is pre-empted by a higher priority thread

11
Different Stages of a Thread
A thread can be in any of the five following states
 Newborn State: When a thread object is created a new thread is born and said to be
in Newborn state.
 Runnable State: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor. If all threads in queue
are of same priority then they are given time slots for execution in round robin
fashion

 Running State: It means that the processor has given its time to the thread for
execution.
 Blocked State: If a thread is prevented from entering into runnable state and
subsequently running state, then a thread is said to be in Blocked state.
 Dead State: A runnable thread enters the Dead or terminated state when it completes
its task or otherwise terminates.
12
A single threaded program

class ABC
{
….
public static void main(..) begin

{
…. body
….
....
}
end
}

13
Multithreaded Program
A Multithreaded Program
Main Thread

start
start
start

Thread A Thread B Thread C

Threads may switch or exchange data/results


14
Single and Multithreaded Processes
threads are light-weight processes within a process

Single-threaded Process Multiplethreaded


Threads of Process
Execution

Single instruction stream


Common
Address Space
15
Main Thread
Every time a Java program starts up, one thread begins running which
is called as the main thread of the program because it is the one that is
executed when your program begins.

Child threads are produced from main thread

Main thread is the last thread to finish execution as it performs


various shut down operations

16
Thread Creation
There are two ways to create thread

1.Extend java.lang.Thread class


run() method must be overridden (similar to main method of sequential program)
run() is called when execution of the thread begins
A thread terminates when run() returns
start() method invokes run()
Calling run() does not create a new thread

2. Implement java.lang.Runnable interface

17
1st method: Extending Thread class
Create a class by extending Thread class and override
run() method:
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}

Create a thread:
MyThread thr1 = new MyThread();

Start Execution of threads:


thr1.start();

Create and Execute: // Both the above can be combined


18 new MyThread().start();
Thread class and Runnable interface
There are several differences between Thread class and Runnable interface
based on their performance, memory usage, and composition.

By extending thread, there is overhead of additional methods, i.e. they


consume excess or indirect memory, computation time, or other
resources.
Since in Java, we can only extend one class, and therefore if we extend
Thread class, then we will not be able to extend any other class. That is
why we should implement Runnable interface to create a thread.
Runnable makes the code more flexible as, if we are extending a thread,
then our code will only be in a thread whereas, in case of runnable, one can
pass it in various executor services, or pass it to the single-threaded
environment.
19 Maintenance of the code is easy if we implement the Runnable interface.
Thread Class
Thread class provide constructors and methods to create and perform
operations on a thread.
Thread class extends Object class and implements Runnable
interface.

Commonly used Constructors of Thread class:


Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

20
Commonly used methods of Thread class
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread. JVM calls the
run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number
of milliseconds.

public void join(): waits for a thread to die.


public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
21
Commonly used methods of Thread class
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of
the thread.
public Thread currentThread(): returns the reference of
currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the
thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread
object to temporarily pause and allow other threads to
execute.
public void suspend(): is used to suspend the
22 thread(depricated).
Commonly used methods of Thread class
public void resume(): is used to resume the suspended
thread(depricated).
public void stop(): is used to stop the
thread(depricated).
public boolean isDaemon(): tests if the thread is a
daemon thread.
public void setDaemon(boolean b): marks the thread
as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has
been interrupted.
public static boolean interrupted(): tests if the
23
current thread has been interrupted.
Runnable interface
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.

24
Starting a Thread
start() method of Thread class is used to start a newly created
thread. It performs following tasks:

A new thread starts(with new callstack).

The thread moves from New state to the Runnable state.

When the thread gets a chance to execute, its target run() method will
run.

25
Method 1: Thread creation by extending Thread class
class MultithreadingDemo extends Thread
{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj1=new MultithreadingDemo();
MultithreadingDemo obj2=new MultithreadingDemo();
obj1.start();
obj2.start();
} Output:
} My thread is in running state.
26 My thread is in running state.
Method 2: Thread creation by implementing Runnable Interface
//A Simple Example If you are not extending the
class MultithreadingDemo implements Runnable Thread class,your class object
would not be treated as a
{ thread object.
public void run(){
System.out.println("My thread is in running state."); So you need to explicitly create
Thread class object.
}
We are passing the object of
public static void main(String args[]) your class that implements
{ Runnable so that your class
MultithreadingDemo obj=new MultithreadingDemo(); run() method may execute.
Thread tobj =new Thread(obj);
Thread tobj =new Thread(new MultithreadingDemo()); //Another way to create
tobj.start();
}
}

27 Output: My thread is in running state.


Java Thread Priority

Priority of a thread describes how early it gets execution and selected


by the thread scheduler.
In Java, when we create a thread, always a priority is assigned to it.

In a Multithreading environment, the processor assigns a priority to a


thread scheduler.

The priority is given by the JVM or by the programmer itself explicitly.


The range of the priority is between 1 to 10 and there are three constant
variables which are static and used to fetch priority of a Thread.

28
Thread Priority in Java Multi-Threading
When we talk about thread we use terms like concurrent threads or
threads executing concurrently.

But in reality threads also run one at a time (at least in a single CPU
system), threads are given CPU cycle in a time shared manner to
simulate concurrency.

The order in which multiple threads will be executed is decided


by thread scheduler and thread priority is used by the thread
scheduler to make that decision.

29
Java Thread Priority
They are as following:

1. public static int MIN_PRIORITY


It holds the minimum priority that can be given to a thread. The value for this is 1.

2. public static int NORM_PRIORITY


It is the default priority that is given to a thread if it is not defined. The value for this is
5.

3. public static int MAX_PRIORITY


It is the maximum priority that can be given to a thread. The value for this is 10.
30
When a thread is created in Java, it inherits its priority from the thread that
creates it.
Thread's priority can be modified at any time after its creation using the
setPriority() method which is a member of Thread class.

General form of setPriority() method


public final void setPriority(int newPriority)
Here newPriority specifies the new thread priority setting for the calling
thread.
Thread priority in Java ranges from 1 (least important) to 10 (most
important) and the default priority level is 5 .
public final intgetPriority()
In Java, getPriority() method is in java.lang.Thread package. it is used to
31 get the priority of a thread.
Three constants in java thread priority
In Java Thread class, three constants are provided to define min, max and default
priority of a thread.

/* The minimum priority that a thread can have. */


public final static int MIN_PRIORITY = 1;

/* The default priority that is assigned to a thread. */


public final static int NORM_PRIORITY = 5;

/* The maximum priority that a thread can have. */


public final static int MAX_PRIORITY = 10;
32
Program
class MyThread extends Thread
{

public void run()


{ System.out.println("Thread Running...");
} OUTPUT
public static void main(String[]args) P1 thread priority : 5
{ Thread Running...
P2 thread priority : 5
MyThread p1 = new MyThread(); P3 thread priority : 5
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
p1.start();
System.out.println("P1 thread priority : " + p1.getPriority());
System.out.println("P2 thread priority : " + p2.getPriority());
System.out.println("P3 thread priority : " + p3.getPriority());
33
} }
Set Priority
class MyThread extends Thread Output
thread priority : 2
{ Thread Running...
public void run()
{
System.out.println("Thread Running...");
}
public static void main(String[]args)
{ MyThread p1 = new MyThread();
p1.start(); // Starting thread
p1.setPriority(2); // Setting priority
int p = p1.getPriority(); // Getting priority
System.out.println("thread priority : " + p);
}
34 }
Set and get Priority
class MyThread extends Thread
{
public void run()
{ System.out.println("Thread Running... "+Thread.currentThread().getName()); }
public static void main(String[] args)
{ MyThread p1 = new MyThread();
Thread Running...
MyThread p2 = new MyThread(); Thread-0 first thread priority :
p1.start(); // Starting thread 5 second thread priority : 1
Thread Running...
p2.start(); Thread-1
p1.setPriority(2); // Setting priority
p2.setPriority(1);
int p = p1.getPriority(); // Getting -priority
int p22 = p2.getPriority();
System.out.println("first thread priority : " + p);
System.out.println("second thread priority : " + p22);
35
}}
Priority Program
public class ThreadPriority extends Thread
{
public void run() {
System.out.println("run() method");
String threadName = Thread.currentThread().getName();
Integer threadPrio = Thread.currentThread().getPriority();
System.out.println(threadName + " has priority " + threadPrio);
}
public static void main(String[] args) throws InterruptedException
{
ThreadPriority t1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
ThreadPriority t3 = new ThreadPriority();
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
t3.start(); }}
36
Write a program to display all running threads in Java.
class RunningThread extends Thread
{
public static void main(String[] args)
{
System.out.println("Main methods");
RunningThread obj = new RunningThread();
//set the thread name2
obj.setName("\nThreadName ");
//calling run () method
obj.start();

ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();


int numThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[numThreads];
currentGroup.enumerate(lstThreads);
//System.out.println(currentThread);
for (int i =1;i< numThreads ; i++)
{
System.out.println("Number of thread: "+i + " " + lstThreads[i].getName());
}

//checking the current running thread


37 Thread currentThread = Thread.currentThread();
System.out.println("Current running thread: "+currentThread }}
Write a program that creates 2 threads - each displaying a message (Pass the message as a parameter to the
constructor). The threads should display the messages continuously till the user presses ctrl+c.

class Thread1 extends Thread


{ class Thread2 extends Thread
String msg = ""; {
Thread1(String msg) String msg = "";
class ThreadDemo
{ Thread2(String msg) {
{ public static void main(String[] args)
this.msg = msg; {
this.msg = msg;
} Thread1 t1 = new Thread1("Running Thread1....");
} Thread1 t2 = new Thread1("Running Thread2....");
public void run() public void run() t1.start();
{ { t2.start(); }}
try {
try {
while (true) {
while (true){ System.out.println(msg);
System.out.println(msg); Thread.sleep(400);
Thread.sleep(300); } }
} } catch (Exception ex)
{
catch (Exception ex) ex.printStackTrace();
{ } }}
38 ex.printStackTrace();
} }}
Important Note:
Thread priorities cannot guarantee that a higher priority thread will
always be executed first than the lower priority thread.
The selection of the threads for execution depends upon the thread
scheduler which is platform dependent.

39
References:
 https://www.geeksforgeeks.org/
 https://www.javatpoint.com/exception-handling-in-java
 https://www.tutorialspoint.com/java/java_exceptions.htm
 The complete reference, eleventh edition, available at:
https://gfgc.kar.nic.in/sirmv-science/GenericDocHandler/1
38-a2973dc6-c024-4d81-be6d-5c3344f232ce.pdf

40
Thank you

41
Multiprogramming vs Multitasking

42
Multithreading
Multithreading is a conceptual programming concept where a program (process)
is divided into two or more subprograms (process), which can be implemented at
the same time in parallel.

A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread, and each thread defines a separate
path of execution.

A process consists of the memory space allocated by the operating system that can
contain one or more threads.

A thread cannot exist on its own; it must be a part of a process .

43
Multitasking
There are two distinct types of Multitasking i.e.

Processor-Based and

Thread-Based multitasking.

44
Comparison

Process-based Multitasking (Multiprocessing)


Each process has an address in memory. In other words, each
process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for
saving and loading registers, memory maps, updating lists, etc.

Thread-based Multitasking (Multithreading)


Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
45
Difference between thread-based and process-based multitasking

As both are types of multitasking there is very basic difference between the
two.
Process-Based multitasking is a feature that allows your computer to run
two or more programs concurrently. For example you can listen to music
and at the same time chat with your friends on Facebook using browser.

In Thread-based multitasking, thread is the smallest unit of code, which


means a single program can perform two or more tasks simultaneously.
For example a text editor can print and at the same time you can edit text
provided that those two tasks are perform by separate threads

46
Process & Multithreading

Threads are independent.


If there occurs exception
in one thread, it doesn't
affect other threads.
It uses a shared memory
area.

47
Multitasking thread requires less overhead
than multitasking processor
A multitasking thread requires less overhead than multitasking processor because
of the following reasons:

Processes are heavyweight tasks where threads are lightweight

Processes require their own separate address space where threads share the
address space

Interprocess communication is expensive and limited where Interthread


communication is inexpensive, and context switching from one thread to the
next is lower in cost.

48
49
50

You might also like