You are on page 1of 36

DFC30133 OBJECT ORIENTED

PROGRAMMING

MultiThreading
Learning Outcomes
1. Define thread and its uses in Java program.
2. Explain the different types of thread:
a. Single thread
b. Multiple thread
3. Differentiate between multitasking and
multithreading.
4. List the methods involved in the life cycle of a
thread.
5. Write multithreaded application.
6. Apply the concept of Runnable Interface.
7. Integrate the concept of threading with GUI.
Thread
• Thread can be defined as single, sequential flow of control
within a program.
• A thread is a lightweight sub process, a smallest unit of
processing. It is a separate path of execution
• Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads. It shares a common
memory area.
• Two types:
1. Single thread
2. Multiple threads
Multithreading
• Multithreading in java is a process of
executing multiple threads simultaneously.
• Multiprocessing and multithreading, both are
used to achieve multitasking.
• But we use multithreading than
multiprocessing because threads share a
common memory area.
• Java Multithreading is mostly used in games,
animation etc.
12/1/2021
Advantages of Multithreading
• It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.
• You can perform many operations together
so it saves time.
• Threads are independent so it doesn't affect
other threads if exception occur in a single
thread.

12/1/2021
Single threaded Application
• A task or process that is made up of only
one thread is single-thread.
• A program that supports single thread is
called single threaded application.
Multi-threaded Application
• A task or process that is made of more
than one thread is multiple threading.
• A program that supports more than one
thread is multi-threaded application
Multi-tasking
• Is the ability of an operating system to
execute more than one program
simultaneously.
• Multitasking can be achieved by two ways:
– Process-based Multitasking(Multiprocessing)
– Thread-based Multitasking(Multithreading)
Difference Between Multiprocessing and Multithreading

No Multiprocessing Multithreading

1. More than one program More than one part of a program


gets executed called threads is executed
simultaneously. simultaneously.

2. Multiprocessing is a Multithreading is also a


timesharing process. CPU timesharing process. CPU
switches from one program switches from one activity to
to another program so another activity within the
quickly to complete all the program so quickly to complete
programs simultaneously. all the activities simultaneously.

3. Since each program Multithreading is a light weight


occupies different memory process because the activities/
location, Multiprocessing is threads share the same memory
called as heavyweight space.
process.
Uses of Threads
• A program can be split into separate tasks
and further into threads. This increases the
effective usage of CPU during execution.
• The popularity of threading increased with
Graphical User Interfaces. Threading system
allowed the user to achieve better
performance in a program. The introduction
of threads created an illusion that the
program's performance was faster.
Importance of Threads
• In a Java program, one thread need not wait
for another thread to complete. This is called
asynchronous behavior of threads.
• Java provides few techniques to handle the
asynchronous behavior of threads.
• Minimize the CPU's idle time.
Single Threaded Program - Example
class Thread_1
{
public static void main(String args[])
{
………
………
………
}
}
Creating Threads
In a single threaded application, main() itself
acts as a thread.
If a program requires more than one thread, it
needs to be created

………………..
………………..
………………..

Main Thread

……………….. Switching ………………..


……………….. ………………..
……………….. ………………..

Thread 1 Thread 2
Declaring a Thread class – General Syntax
class <new thread> extends Thread
{
……………..
……………..
……………..
……………..
……………..
}
Declaring a Thread Class - Example

class Thread_2 extends Thread


{
……………..
……………..
……………..
……………..
……………..
}
Starting new Thread - Example

Thread_2 obj = new Thread_2();


obj.start();

Syntax
Threadname objectname = new Threadname;
objectname.start();
Implementing the run() method
public void run()
{
……………
……………
……………
……………
……………
}
Stopping and Blocking Threads
A thread during the running state can be moved
to the not runnable state. This can be achieved
by:
• Stopping a thread
• Blocking a thread
Stopping a Thread - Syntax

objectname.stop();

Stopping a Thread - Example

obj.stop();
Blocking a Thread
A thread can be temporarily suspended or blocked
from running. The thread is blocked from entering
the runnable or running state. A thread can be
blocked using any of the three methods.
sleep() - The thread is blocked for a specified time.
The thread returns to the runnable state when
the specified time is elapsed.
suspend() - The thread is suspended until further
ordered. The resume() method is called.
wait() - The thread is blocked until a condition
occurs. The notify() method is called.
Methods in Thread Class
Methods Description

Used to initiate the thread.


start()
Used to kill the thread.
stop()
Used to implement the body of the thread and its
run() behaviour.

Used to give the control to another thread of equal


yield() priority.

Used to suspend the thread.


suspend()
Used to resume the suspended thread.
resume()
Methods in Thread Class –Contd…
Used to specify the time frame for suspension.
sleep(t)

Used to make the thread wait until some event


wait() occurs.

Used to schedule the thread to run again.


notify()
Lab Exercise
1. Write a program that has two threads. One thread
should calculate the square of a number while
the other thread should calculate the cube of
another number. Display the square and cube of
the numbers.
2. Write a program that has three threads. One
thread should calculate the area of the circle; the
second thread should calculate the area of a
square; and the third thread should calculate the
area of triangle. Display the results.
Life Cycle of a Thread

New Thread Runnable Not runnable

run() method terminates.


Dead
States of Threads
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state.
States in a Life Cycle of a Thread
States Description

Newborn When a thread is created.

Runnable It is ready for execution and is waiting for


the availability of CPU.

Running It is the time given for the execution of the


thread.

Non-Runnable (Blocked) The thread is suspended, sleeping or


waiting to fulfill certain requirements.

Terminated (Dead) A thread completes executing the run()


method, ends its life.
Newborn State
• A thread object when created is said to be in
newborn state.
• In this state, the thread can be schedule for running
state either using start() method or kill it using stop()
method.
Runnable State
• A thread when ready for execution and is waiting for the availability
of CPU said to be in runnable state.
• The thread in this state joins the queue of threads that are waiting
for execution.
• The threads in the queue are executed based on the given priority.
• The thread gives up the control to another thread of equal priority
using the yield() method.
Running State
• A thread when given time for its execution is
said to be in running state.
• The thread runs until it loses the control on its
own or a higher priority thread prevents it.
suspend() method
• The thread is suspended using suspend() method. A
suspended thread can be revived using the resume()
method.
• This is possible when a thread is required to be
suspended for sometime but is not killed.
sleep() method
• The thread is suspended using sleep(t) method.
• A suspended thread can be revived using the resume()
method.
• This is possible when a thread is required to be
suspended for sometime but is not killed.
wait() method
• The thread is made to wait until some event
occurs. This is done using wait()
• The thread is scheduled to run again using notify()
Blocked State
• When the thread is suspended, sleeping or
waiting to fulfil certain requirements, the thread
is said to be in a blocked state.
• The blocked thread is neither in a runnable
state nor in a dead state.
Dead State
• A thread that has completed the run() method,
ends its life.
• The thread is in the dead state. When a thread
is stopped implementing the stop() method it
has reached the dead state.
Java Thread Example by Extending
Thread Class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

12/1/2021
Java Thread Example by Implementing
Runnable Interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
12/1/2021

You might also like