0% found this document useful (0 votes)
2 views26 pages

2_Multithreading

Multithreading in Java allows multiple threads to execute simultaneously, sharing a common memory area, which saves memory and reduces context-switching time compared to multiprocessing. Threads are lightweight, independent, and can perform multiple operations concurrently without blocking the user. The document also outlines the lifecycle of a thread, methods for creating threads, and the role of the thread scheduler in managing thread execution.

Uploaded by

jayakodycharuka
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)
2 views26 pages

2_Multithreading

Multithreading in Java allows multiple threads to execute simultaneously, sharing a common memory area, which saves memory and reduces context-switching time compared to multiprocessing. Threads are lightweight, independent, and can perform multiple operations concurrently without blocking the user. The document also outlines the lifecycle of a thread, methods for creating threads, and the role of the thread scheduler in managing thread execution.

Uploaded by

jayakodycharuka
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
You are on page 1/ 26

2.

Multithreading
Multithreading in Java
• Multithreading in java is a process of executing multiple
threads simultaneously.

• Thread is basically a lightweight sub-process, a smallest unit


of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.

• But we use multithreading than multiprocessing because


threads share a common memory area. They don't allocate
separate memory area so saves memory, and context-
switching between the threads takes less time than process.

• Java Multithreading is mostly used in games, animation etc.


Advantage of Java Multithreading

1) It doesn't block the user because threads are independent


and you can perform multiple operations at 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


exception occur in a single thread.
Multitasking

• Multitasking is a process of executing multiple tasks


simultaneously. We use multitasking to utilize the CPU.

• Multitasking can be achieved by two ways:

• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)

• Each process have its own address in memory i.e. each


process allocates separate memory area.
• Process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another require some time
for saving and loading registers, memory maps, updating lists
etc.
2) Thread-based Multitasking (Multithreading)

• Threads share the same address space.


• Thread is lightweight.
• Cost of communication between the thread is low.

• Note: At least one process is required for each thread.


What is Thread in java
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.
• As shown in the above figure, thread is executed inside
the process.
• There is context-switching between the threads.
• There can be multiple processes inside the OS and one
process can have multiple threads.
Life cycle of a Thread (Thread States)

A thread can be in one of the five states.

– According to sun, there is only 4 states in thread life cycle


in java new, runnable, non-runnable and terminated.
There is no running state.

– But for better understanding the threads, we are


explaining it in the 5 states I.e traditional way.
The life cycle of the thread in java is controlled by JVM. The
java thread states are as follows:

• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated (Dead)
States
• New : only Thread object is created in this state.It is in this
state before the start() invoked.
• Runnable/ready to run : life of thread starts from this state. It
enters into this first time by calling start( ) and several times
later.
• Running state: A thread is assigned a processor and is
running. The thread enters this state only after it is in the
Runnable state and scheduler assigns a processor to the
thread.
• Sleeping/waiting/blocked state: When sleep method is
invoked on a running thread it enteres the sleeping mode. It
returns to the runnable state when the sleep interval ends.
• Dead state: This is the last state of the thread. When run
method ends the thread is terminated. Once terminated a
thread cannot be terminated.
• How to create thread

• There are two ways to create a thread:

• 1) By extending Thread class


• 2) By implementing 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)
– Thread(ThreadGroup grp, Runnable Ob)
– Thread(ThreadGroup grp, String name)
– Thread(ThreadGroup grp, Runnable Ob,Stringname)
– Thread(ThreadGroup grp, Runnable ob,String name, long
mSec)
• Commonly used methods of Thread class:
• 1) public void run(): is used to perform action for a thread.
• 2) public void start(): starts the execution of the thread.JVM
calls the run() method on the thread.
• 3) public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily pause execution) for the
specified number of milliseconds.
• 4) public void join(): waits for a thread to die.
• 5) public void join(long miliseconds): waits for a thread to die for
the specified miliseconds.
• 6) public int getPriority(): returns the priority of the thread.
• 7) public int setPriority(int priority): changes the priority of the
thread.
• 8) public String getName(): returns the name of the thread.
• 9) public void setName(String name): changes the name of the
thread.
10) public Thread currentThread(): returns the reference of currently
executing thread.
11) public int getId(): returns the id of the thread.
12) public Thread.State getState(): returns the state of the thread.
13) public boolean isAlive(): tests if the thread is alive.
14) public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15) public void suspend(): is used to suspend the thread(depricated).
16) public void resume(): is used to resume the suspended
thread(depricated).
17) public void stop(): is used to stop the thread(depricated).
18) public void setDaemon(boolean b): marks the thread as daemon or user
thread.
19) public void interrupt(): interrupts the thread.
20) public boolean isInterrupted(): tests if the thread has been interrupted.
21) public static boolean interrupted(): tests if the current thread has been
interrupted.
Steps to create thread by extending Thread class

• Define a class which extends Thread class


• In this class define the thread method.
• Create an object of this class
• Invoke the start method on this object. The start method gives a call to
• the run method.

• The main Thread


– Whwn a java program starts running, a thread called main starts
running. Every java program runs as a thread. When this thread
stops running the program terminates.
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().

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


Steps to create Thread by implementing Runnable interface:

• Define a class which implements Runnable interface.


• Define run method in it.
• Create an object of this class
• Create an object of Thread class using Runnable object.
• Invoke the start method on thread object to execute the thread.
Who makes your class object as thread object?

• Thread class constructor allocates a new thread object.When you


create object of Multi class,your class constructor is invoked(provided
by Compiler) from where Thread class constructor is invoked(by super()
as first statement).So your Multi class object is thread object now.(
Example UsingThread.java)

• If you are not extending the Thread class,your class object would not be
treated as a thread object.So you need to explicitely create Thread
class object.We are passing the object of your class that implements
Runnable so that your class run() method may execute.(Example
UsingRunnable.java)
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.
Running Multiple Threads:

• The main thread can create several child threads and each thread will
run independently. A thread schedular manages the execution of
threads and assigns the CPU to each thread.

• Example MultipleThreadWithoutSleep.java

• You can get the different outputs everytime.


• This decides the thread scheduler.
Thread Scheduler in Java

• Thread scheduler in java is the part of the JVM that decides which
thread should run.
• There is no guarantee that which runnable thread will be chosen to run
by the thread scheduler.
• Only one thread at a time can run in a single process.
• Thread priorities, load on the CPU, availability of resources and type of
scheduling decides which thread should execute.
• The thread scheduler mainly uses preemptive or time slicing scheduling
to schedule the thread
• Difference between preemptive and time slicing
– Under preemptive scheduling, the highest priority task executes until
it enters the waiting or dead states or a higher priority task comes
into existence. Under time slicing, a task executes for a predefined
slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based
on priority and other factors.
Sleep method in java

• In java sleep() method of Thread class is used to sleep a thread for the
specified milliseconds of time.
• We can pause a running thread using a sleep method.
• This method throws an interruptedException when it is interrupted by
another thread.

• Syntax of sleep() method in java


• public static void sleep(long miliseconds)throws InterruptedException

• Example MultipleThreadWithSleep.java
• In our program we have given a delay of 2 seconds between
messages. So when a thread is paused the other thread will get control
and execute.
Can we start a thread twice?

• No. After staring a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown.
• For Example: TwiceThread.java
What if we call run() method directly instead start() method?

• Each thread starts in a separate call stack.


• Invoking the run() method from main thread, the run() method goes
onto the current call stack rather than at the beginning of a new call
stack.
• Example RunDirect.java , RunDirect2.java

You might also like