[go: up one dir, main page]

0% found this document useful (0 votes)
37 views30 pages

CSE Module 5

Uploaded by

motoh6220
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)
37 views30 pages

CSE Module 5

Uploaded by

motoh6220
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/ 30

MultiThreading

Dr. S Sudheer Mangalampalli


Assistant Professor, Senior Grade1
School of Computer Science and Engineering
VIT-AP University

June 29, 2022

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
1 / 30
Multithreading in Java

1 Multithreading in Java is a process of executing multiple threads


simultaneously.
2 A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
3 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.
4 Java Multithreading is mostly used in games, animation, etc.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
2 / 30
Java Multithreading

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
3 / 30
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.
Multitasking Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU. Multitasking can
be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
4 / 30
Process-based Multitasking and Thread-based Multitasking

Process-based Multitasking
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
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
5 / 30
What is Thread in java

A thread is a lightweight subprocess, the 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 uses a shared memory area.
A 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.
Note: At a time one thread is executed only.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
6 / 30
Java Thread class

1 Java provides Thread class to achieve thread programming.


2 Thread class provides constructors and methods to create and
perform operations on a thread.
3 Thread class extends Object class and implements Runnable interface.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
7 / 30
Java Threads — How to create a thread in Java

There are two ways to create a thread:


By extending Thread class
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.
Life cycle of a Thread (Thread States) In Java, a thread always exists
in any one of the following states. These states are:
New
Active
Blocked / Waiting
Timed Waiting
Terminated

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
8 / 30
Lifecycle of a Thread

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
JuneVIT-AP
29, 2022University
9 / 30
By extending Thread class

import java . io . ∗ ;
import java . u t i l . ∗ ;
p u b l i c c l a s s GFG e x t e n d s Thread {
// i n i t i a t e d r u n method f o r Thread
p u b l i c void run ( )
{
System . o u t . p r i n t l n ( ” Thread S t a r t e d Running . . . ” ) ; }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
{
GFG g1 = new GFG ( ) ;
// i n v o k i n g Thread
g1 . s t a r t ( ) ; } }

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
10 / 30
By extending Runnable Interface

import java . io . ∗ ;
import java . u t i l . ∗ ;
p u b l i c c l a s s GFG1 i m p l e m e n t s R u n n a b l e {
// method t o s t a r t Thread
p u b l i c void run ( )
{ System . o u t . p r i n t l n ( ” Thread i s Running S u c c e s s f u l l y ” ) ;
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
{
GFG1 g1 = new GFG1 ( ) ;
// i n i t i a l i z i n g Thread O b j e c t
Thread t 1= new Thread ( g1 ) ;
t1 . s t a r t ( ) ; } }

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
11 / 30
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 cease 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.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
12 / 30
Commonly used methods of Thread class:

1 public String getName(): returns the name of the thread.


2 public void setName(String name): changes the name of the thread.
3 public Thread currentThread(): returns the reference of currently
executing thread.
4 public int getId(): returns the id of the thread.
5 public Thread.State getState(): returns the state of the thread.
6 public boolean isAlive(): tests if the thread is alive.
7 public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
8 public void suspend(): is used to suspend the thread.
9 public void resume(): is used to resume the suspended
thread(depricated).
10 public void stop(): is used to stop the thread(depricated).

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
13 / 30
Commonly used methods of Thread class:

1 public boolean isDaemon(): tests if the thread is a daemon thread.


2 public void setDaemon(boolean b): marks the thread as daemon or
user thread.
3 public void interrupt(): interrupts the thread.
4 public boolean isInterrupted(): tests if the thread has been
interrupted.
5 public static boolean interrupted(): tests if the current thread has
been interrupted.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
14 / 30
Thread.sleep() method in Java

Thread Class is a class that is basically a thread of execution of the


programs. It is present in Java.lang package.
Thread class contains the Sleep() method.
There are two overloaded methods of Sleep() method present in
Thread Class, one is with one argument and another one is with two
arguments.
The sleep() method is used to stop the execution of the current
thread(whichever might be executing in the system) for a specific
duration of the time and after that time duration gets over, the
thread which is executing earlier starts to execute again.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
15 / 30
Thread.sleep() method in Java

Method Whenever Thread.sleep() functions to execute, it always


pauses the current thread execution.
If any other thread interrupts when the thread is sleeping, then
InterruptedException will be thrown.
If the system is busy, then the actual time the thread will sleep will be
more as compared to that passed while calling the sleep method and
if the system has less load, then the actual sleep time of the thread
will be close to that passed while calling sleep() method.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
16 / 30
Using Thread.Sleep() Method For Main Thread

import java . io . ∗ ;
i m p o r t j a v a . l a n g . Thread ;
c l a s s GFG2 {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
try {
f o r ( i n t i = 0 ; i < 5 ; i ++) {
Thread . s l e e p ( 1 0 0 0 ) ;
System . o u t . p r i n t l n ( i ) ; } }
catch ( Exception e ) {
System . o u t . p r i n t l n ( e ) ;
}}}

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
17 / 30
Using Thread.Sleep() Method For Custom Thread

import java . io . ∗ ;
i m p o r t j a v a . l a n g . Thread ;
c l a s s GFG3 e x t e n d s Thread {
p u b l i c void run ( )
{ try {
f o r ( i n t i = 0 ; i < 5 ; i ++) {
Thread . s l e e p ( 1 0 0 0 ) ;
System . o u t . p r i n t l n ( i ) ; }}
catch ( Exception e ) {
System . o u t . p r i n t l n ( e ) ;
} }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
GFG o b j = new GFG ( ) ;
obj . s t a r t ( ) ;
}}

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
18 / 30
IllegalArguementException When Sleep Time Is Negative

import java . io . ∗ ;
i m p o r t j a v a . l a n g . Thread ;
c l a s s GFG5 {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
try {
f o r ( i n t i = 0 ; i < 5 ; i ++) {
Thread . s l e e p ( −100);
System . o u t . p r i n t l n ( i ) ;
}}
catch ( Exception e ) {
System . o u t . p r i n t l n ( e ) ;
}}}

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
19 / 30
Joining Threads in Java

java.lang.Thread class provides the join() method which allows one


thread to wait until another thread completes its execution.
If t is a Thread object whose thread is currently executing, then
t.join() will make sure that t is terminated before the next instruction
is executed by the program.
If there are multiple threads calling the join() methods that means
overloading on join allows the programmer to specify a waiting period.
However, as with sleep, join is dependent on the OS for timing, so you
should not assume that join will wait exactly as long as you specify.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
20 / 30
Joining Threads in Java

There are three overloaded join functions.


join(): It will put the current thread on wait until the thread on which it
is called is dead. If thread is interrupted then it will throw
InterruptedException.
Syntax
public f i n a l void join ()
join(long millis):It will put the current thread on wait until the thread on
which it is called is dead or wait for specified time (milliseconds).
public f i n a l synchronized void j o i n ( long m i l l i s )
join(long millis, int nanos): It will put the current thread on wait until
the thread on which it is called is dead or wait for specified time
(milliseconds + nanos).
p u b l i c f i n a l s y n c h r o n i z e d v o i d j o i n ( long m i l l i s , i n t na

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
21 / 30
Example for Join method

import java . io . ∗ ;
c l a s s T h r e a d J o i n i n g e x t e n d s Thread
{
p u b l i c void run ( )
{
f o r ( i n t i = 0 ; i < 2 ; i ++){
try
{
Thread . s l e e p ( 1 0 0 0 ) ;
System . o u t . p r i n t l n ( ” C u r r e n t Thread : ”+ Thread . c u r r e n t T
c a t c h ( E x c e p t i o n ex ) {
System . o u t . p r i n t l n ( ” E x c e p t i o n h a s ” +” been c a u g h t ” + e
System . o u t . p r i n t l n ( i ) ; } } }

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
22 / 30
c l a s s GFG6
{
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
{
T h r e a d J o i n i n g t 1 = new T h r e a d J o i n i n g ( ) ;
T h r e a d J o i n i n g t 2 = new T h r e a d J o i n i n g ( ) ;
T h r e a d J o i n i n g t 3 = new T h r e a d J o i n i n g ( ) ;
t1 . s t a r t ( ) ;
try {
System . o u t . p r i n t l n ( ” C u r r e n t Thread : ”+ Thread . c u r r e n t T
t 1 . j o i n ( ) ; } c a t c h ( E x c e p t i o n ex ) {
System . o u t . p r i n t l n ( ” E x c e p t i o n h a s ” +”been c a u g h t ” + e
t2 . s t a r t ( ) ;
try {
System . o u t . p r i n t l n ( ” C u r r e n t Thread : ”+ Thread . c u r r e n t T
t 2 . j o i n ( ) ; } c a t c h ( E x c e p t i o n ex ) {
System . o u t . p r i n t l n ( ” E x c e p t i o n h a s been ” +” c a u g h t ” + e
t3 . s t a r t ( ) ; } }
Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1
MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
23 / 30
Priority of a Thread

Each thread has a priority. Priorities are represented by a number


between 1 and 10.
In most cases, the thread scheduler schedules the threads according
to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
24 / 30
import java . lang . ∗ ;
p u b l i c c l a s s T h r e a d P r i o r i t y E x a m p l e e x t e n d s Thread
{ p u b l i c void run ( )
{
System . o u t . p r i n t l n ( ” I n s i d e t h e r u n ( ) method ” ) ; }
p u b l i c s t a t i c v o i d main ( S t r i n g a r g v s [ ] )
{
T h r e a d P r i o r i t y E x a m p l e t h 1 = new T h r e a d P r i o r i t y E x a m p l e (
T h r e a d P r i o r i t y E x a m p l e t h 2 = new T h r e a d P r i o r i t y E x a m p l e (
T h r e a d P r i o r i t y E x a m p l e t h 3 = new T h r e a d P r i o r i t y E x a m p l e (
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e t h r e a d t h 1 i s : ”
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e t h r e a d t h 2 i s : ”
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e t h r e a d t h 2 i s : ”
th1 . s e t P r i o r i t y ( 6 ) ;
th2 . s e t P r i o r i t y ( 3 ) ;
th3 . s e t P r i o r i t y ( 9 ) ;

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
25 / 30
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e t h r e a d t h 1 i s : ”
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e t h r e a d t h 2 i s : ”
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e t h r e a d t h 3 i s : ”
System . o u t . p r i n t l n ( ” C u r r e n t l y E x e c u t i n g The Thread : ”
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e main t h r e a d i s : ”
Thread . c u r r e n t T h r e a d ( ) . s e t P r i o r i t y ( 1 0 ) ;
System . o u t . p r i n t l n ( ” P r i o r i t y o f t h e main t h r e a d i s : ”
}}

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
26 / 30
Synchronization in Java

Multi-threaded programs may often come to a situation where


multiple threads try to access the same resources and finally produce
erroneous and unforeseen results.
So it needs to be made sure by some synchronization method that
only one thread can access the resource at a given point in time.
Java provides a way of creating threads and synchronizing their tasks
using synchronized blocks.
Synchronized blocks in Java are marked with the synchronized
keyword. A synchronized block in Java is synchronized on some
object.
All synchronized blocks synchronize on the same object can only have
one thread executing inside them at a time.
All other threads attempting to enter the synchronized block are
blocked until the thread inside the synchronized block exits the block.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
27 / 30
// Only one t h r e a d can e x e c u t e a t a t i m e .
// s y n c o b j e c t i s a r e f e r e n c e t o an o b j e c t
// whose l o c k a s s o c i a t e s w i t h t h e m o n i t o r .
// The code i s s a i d t o be s y n c h r o n i z e d on
// t h e m o n i t o r o b j e c t
synchronized ( sync object )
{
// A c c e s s s h a r e d v a r i a b l e s and o t h e r
// s h a r e d r e s o u r c e s
}

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
28 / 30
Synchronization in Java

This synchronization is implemented in Java with a concept called


monitors. Only one thread can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
29 / 30
Inter thread communication in Java

https://www.youtube.com/watch?v=Ut8YFsi2WR0

Dr. S Sudheer Mangalampalli Assistant Professor, Senior Grade1


MultiThreading
School of Computer Science and Engineering
June 29,
VIT-AP
2022 University
30 / 30

You might also like