Multhreading in Java
Thread Classes, Runnable Interface, Thread priority
Mr. Ajay Singh
Assistant Professor
Department of Computer Science & Engineering
Devbhoomi Uttarakhand University
What is Multithreading
• The process of executing multiple tasks (also called threads)
simultaneously is called multithreading
• The primary purpose of multithreading is to provide simultaneous
execution of two or more parts of a program
• To make maximum use of CPU time
• A multithreaded program contains two or more parts that can run
concurrently
• It enables programmers to write in a way where multiple activities
can proceed simultaneously within a single application
What is Multitasking
• It is the way of executing multiple tasks at a time executing them
concurrently over a specified period
• Multitasking is done in two ways-
1. Process-based multitasking: It is also called multiprocessing where
each process has its address in memory, i.e., each process allocates
separate memory area.
2. Thread-based multitasking: This thread-based multitasking is also
termed as multithreading where threads share the same address
space
Thread-based multitasking
• In thread-based multitasking, threads are considered as the smallest unit
• It signifies that a single program can perform two or more tasks at a time
• For example, a word processing application can let users write a document and
save it along with printing another document, all done simultaneously
• Multitasking threads require less overhead than multitasking processes
• Processes are heavyweight asks that need their own separate address space
• Hence, the interprocess communication becomes expensive and limited
Thread-based multitasking
• A thread is a lightweight sub-process, the smallest unit of processing
• Multiprocessing and multithreading, both are used to achieve
multitasking
• However, we use multithreading than multiprocessing because
threads use a shared memory area
• They don't allocate separate memory area so saves memory
• And, context-switching between the threads takes less time than
process
Thread-based multitasking
• Java Multithreading is mostly used in games, animation, etc.
• Multithreading means that you have multiple threads of execution
inside the same application
• A thread is like a separate CPU executing your application
• A multithreaded application is like an application that has multiple
CPUs executing different parts of the code at the same time
Java Multithreading
• A thread is not equal to a CPU though
• Usually a single CPU will share its execution time among multiple
threads switching between executing each of the threads for a given
amount of time
• It is also possible to have the threads of an application be executed by
different CPUs
Why Multithreading?
• Better utilization of a single CPU.
• Better utilization of multiple CPUs or CPU cores.
• Better user experience with regards to responsiveness.
• Better user experience with regards to fairness.
Advantages of Java
Multithreading:
1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
Life Cycle of a Thread
• A thread goes through various stages of its life cycle
• First of all, a thread is born, started its tasks, run a sequence of tasks
concurrently, and then dies
• Following diagram shows the various stages of a Thread life cycle-
Life Cycle of a Thread
Stages of Thread life cycle
• New Thread: A new thread begins its life cycle in the new state. The
process remains in this condition until the program starts the thread.
• Runnable: As soon as the new thread starts, the thread status
becomes Runnable. At this stage, a thread is considered to execute its
function or working.
• Not Runnable: A Runnable thread when entered the time of waiting
for the state for a specific interval of time. That time, the thread is not
in Runnable condition.
• Dead/Terminated: The Runnable thread enters the end stage when it
completes its tasks.
Two Ways to Implement
Multithreading
1. Using Thread Class
2. Using Runnable Interface
Java Thread class
• Java provides Thread class to achieve thread programming
• Thread class provides constructors and methods to create and
perform operations on a thread
• Thread class extends Object class and implements Runnable interface
Java Thread Methods
Java Thread Methods
Java Thread Methods
Java Thread Methods
Java Thread Methods
Create a Thread by Extending a
Thread Class
Step 1: Override run() Method
• You will need to override run( ) method available in Thread class
• This method provides an entry point for the thread
• You will put your complete business logic inside this method
• Following is a simple syntax of run() method −
Step 2: Call Thread using start()
Method
• Once Thread object is created, you can start it by calling start()
method
• It executes a call to run( ) method
• Following is a simple syntax of start() method −
Example: Create Thread by
Extending Thread Class
Example: Create Thread by
Extending Thread Class
Create a Thread by
Implementing a Runnable
Interface
Follow three basic steps −
• Step 1: Implement run() Method:
1. you need to implement a run() method provided by a Runnable interface
2. This method provides an entry point for the thread and you will put your
complete business logic inside this method
3. Following is a simple syntax of the run() method −
Step 2: Instantiate a Thread
Object
• As a second step, you will instantiate a Thread object using the
following constructor −
• Where,
threadObj is an instance of a class that implements Runnable interface
threadName is the name given to the new thread
Step 3: Call Thread using start()
Method
• Once a Thread object is created, you can start it by calling start()
method, which executes a call to run( ) method
• Following is a simple syntax of start() method −
Example: Create Thread by
Implementing Runnable
Interface
Example: Create Thread by
Implementing Runnable
Interface
Thread priority
“Thread priority is a scheduling hint that tells the
thread scheduler how important a thread is
relative to others. Higher-priority threads are
more likely to be executed before lower-priority
ones”
Priority of a Thread (Thread
Priority)
• Each thread have a priority
• Priorities are represented by a number between 1 and 10
• In most cases, thread schedular schedules threads according to their
priority (known as preemptive scheduling)
• But it is not guaranteed because it depends on JVM that which
scheduling it chooses.
Default priority
• Each thread has a priority value between 1 (lowest) and 10 (highest),
with 5 as the default.
• Default priority of a thread is 5 (NORM_PRIORITY)
• The value of MIN_PRIORITY is 1 and
• the value of MAX_PRIORITY is 10
• Example:
Thread t1 = new Thread();
[Link](Thread.MAX_PRIORITY); // 10
3 constants defined in Thread
class
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Constant Value Meaning
Thread.MIN_PRIORITY 1 Least important
Thread.NORM_PRIORITY 5 Default priority
Thread.MAX_PRIORITY 10 Most important
Working
• The thread scheduler uses priority as a guideline, not a guarantee
• On some systems, priority may be ignored or overridden by OS-level
policies
• Higher-priority threads may preempt lower-priority ones in
preemptive scheduling
• Example Scenario-
• If you have:Thread A with priority 2
• Thread B with priority 8
• Then Thread B is more likely to be scheduled first, especially under heavy CPU
load.
Example of priority of a Thread