SlideShare a Scribd company logo
1 of 53
www.SunilOS.com 1
www.sunilos.com
www.raystec.com
Concurrency/Threads
www.SunilOS.com 2
Process
A process has a self-contained execution
environment. A process generally has a
complete, private set of basic run-time
resources; in particular, each process has its
own memory space.
Most implementations of the Java virtual
machine run as a single process.
www.SunilOS.com 3
Concurrency vs. Parallelism
CPU CPU1 CPU2
www.SunilOS.com 4
Thread
Threads are sometimes called lightweight
processes. Both processes and threads provide an
execution environment, but creating a new thread
requires fewer resources than creating a new
process.
Threads exist within a process — every process
(application) has at least one thread.
Threads share the process's resources, including
memory and open files.
Each thread is associated with an instance of the
class java.lang.Thread.
www.SunilOS.com 5
Threads and Processes
www.SunilOS.com 6
Multitasking & Multithreading
 Multitasking refers to a computer's ability to perform multiple
jobs concurrently. Multitasking means more than one
programs are running together on a single machine.
 A thread is a single sequence of execution within a
program.
 Multithreading refers to multiple threads of control within a
single program. Each program can run multiple threads of
control within it, e.g., Web Browser.
www.SunilOS.com 7
HelloWithoutThread
public class HelloWithoutThread {
String name = null; // Keeps Thread Name
public HelloWithoutThread(String threadName) {// Constructor
name = threadName;
}
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(i + " Hello Thread " + name);
}
}
}
www.SunilOS.com 8
TestWithoutThread
public static void main(String[] args) {
HelloWithoutThread t1 = new
HelloWithoutThread(“Raina");
HelloWithoutThread t2 = new HelloWithoutThread(“Virat");
t1.run();
t2.run();
}
www.SunilOS.com 9
TestWithoutThread Output
 0 Hello Raina
 1 Hello Raina
 2 Hello Raina
 …..
 48 Hello Raina
 49 Hello Raina
 0 Hello Virat
 1 Hello Virat
 2 Hello Virat
 ……..
 48 Hello Virat
 49 Hello Virat
www.SunilOS.com 10
Thread
Raktabija
 Raktabija had a capability
to create another Raktbija
by his single drop of blood.
 Created Raktabija will be
equally powerful, and can
consume same kind of
resources and work
concurrently.
 If one Raktabija dies
another will remain active
and live.
 Likewise a Thread can
create another thread.
 Created threads will be
equally powerful.
 Threads need same kind of
resources to be executed.
 Threads work concurrently.
 If one thread dies, other
will remain active in
memory.
www.SunilOS.com 11
http://en.wikipedia.org/wiki/Raktavija
www.SunilOS.com 12
Creating Threads
 There are two ways to create a Thread object
1. Inherit Thread class.
2. Implement the Runnable.
 In both cases the run() method should be
implemented
www.SunilOS.com 13
HelloWithThread
public class HelloWithThread extends Thread {
private String name = null;
public HelloWithThread(String threadName) {
name = threadName;
}
public void run() {
for (int i = 0; i < 500; i++) {
System.out.println(i + " Hello Thread " + name);
}
}
}
www.SunilOS.com 14
TestWithThread
public static void main(String[] args) {
HelloWithThread t1 = new HelloWithThread(“Raina");
HelloWithThread t2 = new HelloWithThread(“Virat");
t1.start();
t2.start();
for (int i = 0; i < 500; i++) {
System.out.println(" Main Thread ");
}
}
www.SunilOS.com 15
TestWithThread Output
 0 Hello Thread Raina
 1 Hello Thread Raina
 2 Hello Thread Raina
 0 Hello Thread Virat
 1 Hello Thread Virat
 1 Hello Thread main
 2 Hello Thread main
 3 Hello Thread main
 3 Hello Thread Raina
 4 Hello Thread Raina
 2 Hello Thread Virat
 3 Hello Thread Virat
 4 Hello Thread main
 ……..
 48 Hello Thread Raina
 49 Hello Thread Raina
 48 Hello Thread Virat
www.SunilOS.com 16
Scheduling Threads
I/O operation completes
start()
Currently executed
thread
Ready queue
•Waiting for I/O operation to be completed
•Waiting to be notified
•Sleeping
•Waiting to enter a synchronized section
Newly created
threads
What happens when
a program with a
ServerSocket calls
accept()?
www.SunilOS.com 17
Thread State Diagram
Alive
New Thread Dead Thread
Running
Runnable
new ThreadExample();
run() method returns
while (…) { … }
Blocked
Object.wait()
Thread.sleep()
blocking IO call
waiting on a monitor
thread.start();
www.SunilOS.com 18
Thread Lifecycle
Born
Blocked
Runnable
Dead
stop()
start()
stop()
Active
block on I/O
I/O available
JVM
sleep(500)
wake up
suspend()
resume()
wait
notify
www.SunilOS.com 19
Child of other Class -Runnable Interface
If a class is child of another class and you want to make it
Thread then use Runnable interface since Java does not
support multiple inheritance.
public class HelloThread extends Hello implements Runnable {
public void run() {
System.out.println("Hello from Thread!");
}
public static void main(String args[]) {
HelloThread runThread = new HelloThread ()
Thread th =new Thread(runThread);
th.start();
}
}
www.SunilOS.com 20
Thread Methods
void start()
o Creates a new thread and makes it runnable.
o This method can be called only once.
void run()
o The new thread begins its life inside this method.
void stop() (deprecated)
o The thread is being terminated.
www.SunilOS.com 21
Thread Methods
yield()
o Pauses the currently executing thread object and allows
other thread of same priority to be executed.
sleep(int m)/sleep(int m,int n)  
o The thread is slept for m milliseconds and n
nanoseconds.
www.SunilOS.com 22
Multiple Threads in an Application
Each thread has its private run-time stack.
If two threads execute the same method, each will
have its own copy of the local variables the
methods uses.
However, all threads see the same dynamic
memory (heap).
Two different threads can act on the same object
and same static fields concurrently.
www.SunilOS.com 23
Green Thread
 Native Thread model:
o the threads are scheduled by the OS
o maps a single Java thread to an OS thread
 Green Thread model:
o the threads are scheduled by the Virtual Machine.
o threads are invisible to the OS.
o Green threads emulate multithreaded environments without relying
on any native OS capabilities.
o They run code in user space that manages and schedules threads
o Green threads enables Java to work in environments that do not
have native thread support.
o OS doesn't know anything about the threads used in the VM. It's up
to the VM to handle all the details.
www.SunilOS.com 24
Scheduling
Thread-scheduling is the mechanism used
to determine how runnable threads are
allocated CPU time.
A thread-scheduling mechanism is either
preemptive or non-preemptive .
www.SunilOS.com 25
Preemptive Scheduling
Preemptive scheduling – the thread scheduler
preempts (pauses) a running thread and executes
other thread as per schedule.
Non-preemptive scheduling – the scheduler never
interrupts a running thread. Other thread will get
chance only if current thread dies.
The non-preemptive scheduler relies on the
running thread to yield control of the CPU so that
other threads may execute.
www.SunilOS.com 26
Starvation and Livelock
A non-preemptive scheduler may cause
starvation.
Runnable threads which are in ready queue
may have to wait to be executed for a very
log time or forever.
Sometimes, starvation is also called a
livelock.
www.SunilOS.com 27
Time-sliced Scheduling
 Time-sliced scheduling – the scheduler allocates a period of
time that each thread can use the CPU. When that amount
of time has elapsed, the scheduler preempts the thread and
switches to other thread.
 Non time-sliced scheduler – the scheduler does not use
elapsed time to determine when to preempt a thread. It
uses other criteria such as priority or I/O status.
www.SunilOS.com 28
Java Scheduling
Java-scheduler is preemptive and based on
priority of threads.
It uses fixed-priority scheduling.
Threads are scheduled according to their
priority with respect to other threads in the
ready queue.
www.SunilOS.com 29
Java Scheduling
The highest priority runnable thread is
always selected for execution above lower
priority threads.
When multiple threads have equally high
priority then only one of them will be
guaranteed to be executed.
Java threads are guaranteed to be
preemptive-but not time sliced.
www.SunilOS.com 30
Thread Priority
Every thread has a priority.
When a thread is created, it inherits the
priority of the thread that created it.
The priority values range from 1 to 10, in
increasing priority. That means 1 is lowest
and 10 is highest.
www.SunilOS.com 31
Thread Priority (cont.)
The priority can be adjusted subsequently using
the setPriority(5) method.
The priority of a thread may be obtained using
getPriority().
 Priority constants are defined in Thread class:
o MIN_PRIORITY=1
o MAX_PRIORITY=10
o NORM_PRIORITY=5
Thread th = new Thread(“Raina”);
o th.setPriority(4);
www.SunilOS.com 32
Some Notes
Thread implementation in Java is actually
based on operating system support.
Some Windows operating systems support
only 7 priority levels, so different levels in
Java may actually be mapped to the same
operating system level.
www.SunilOS.com 33
Daemon Threads
Daemon threads are “background” threads, that
provide services to other threads, e.g., the garbage
collection thread.
The Java VM will not exit if non-Daemon threads
are executing.
The Java VM will exit if only Daemon threads are
executing.
Daemon threads will die when the Java VM exits.
t.setDaemon(true)
www.SunilOS.com 34
ThreadGroup
The ThreadGroup class is used to create
groups of similar threads.
www.SunilOS.com 35
ThreadInfo
public class ThreadInfo {
public static void main(String[] args) {
Thread t = new Thread("My Thread");
log(" ",t);
}
public static void log(String indent, Thread t) {
System.out.println(indent + "THREAD Name :" + t.getName());
System.out.println(indent + "ID :" + t.getId());
System.out.println(indent + "Priority :" + t.getPriority());
System.out.println(indent + "State :" + t.getState());
System.out.println(indent + "Thread Group :"
+ t.getThreadGroup().getName());
System.out.println(indent + "Is Alive :" + t.isAlive());
System.out.println(indent + "Is Daemon :" + t.isDaemon() + "n");
}
}
www.SunilOS.com 36
ThreadInfo (Cont..)
public static void info(String indent, ThreadGroup tg) {
int threadCount = tg.activeCount(); //Get Active Thread Count
Thread[] threads = new Thread[threadCount];
tg.enumerate(threads); //Get Active Threads
System.out.println(indent + "THREAD GROUP NAME: " + tg.getName());
System.out.println(indent + "Is Daemon : " + tg.isDaemon());
//Log Threads Details
for (int i = 0; i < threads.length; i++) {
log( indent + "t" , threads[i]);
}
int groupCount = tg.activeGroupCount();//Get Active ThreadGroup Count
ThreadGroup[] groups = new ThreadGroup[groupCount];
tg.enumerate(groups); //Get ThreadGroups
for (int i = 0; i < groups.length; i++) {
info(indent + "t", groups[i]);
}
}
www.SunilOS.com 37
ThreadInfo (Cont..)
public static void main(String[] args) throws Exception{
Thread t = Thread.currentThread(); //Get Currect Thread
ThreadGroup tg = t.getThreadGroup();
while(tg.getParent() !=null){ //Get Root ThreadGroup
tg=tg.getParent() ;
}
HelloWithThread t1 = new HelloWithThread("TRaina");
t1.setPriority(1);
HelloWithThread t2 = new HelloWithThread("Yuvraj");
t2.setPriority(1);
t1.start();
t2.start();
info("", tg);
}
www.SunilOS.com 38
Concurrency
An object in a program can be changed by
more than one threads concurrently.
Q: Is the order of changes that were
preformed on the object important?
Race-Condition
www.SunilOS.com 39
www.SunilOS.com 40
Race Condition
When two threads are simultaneously
modifying a single object, is called race-
condition.
Both threads “race” to store their values in a
single object.
The outcome of a program is affected by the
order in which the program's threads are
allocated CPU time.
www.SunilOS.com 41
Deposit in an Account
Account
User1
User2
Balance = 1000
Balance = 2000
getBalance():1000
setBalance(2000)
setBalance(2000)
getBalance():1000
www.SunilOS.com 42
Synchronized access
AccountUser1
User2
Balance = 1000
Balance = 3000
getBalance():1000
setBalance(2000)
setBalance(3000)
getBalance():2000
Deposit in an Account
www.SunilOS.com 43
Instance vs static attributes
instance
static
instance
static
Attributes Methods
Person
-name : String
-address: String
$ AVR_AGE : int = 60
+getName()
+getAddress()
$ getAveAge()
+getName()
+getAddress()
$ getAveAge()
AVR_AGE = 60
Person p1, p2
p1 = new Person()
p2 = new Person()
Name = A
Address = Add1
Name = B
Address = Add2
p1
p2p1.getName ()
P2.getAvrAge()
Person.getAvrAge()
Class
1011
1010
1010
1011
2B
2B
www.SunilOS.com 44
Account
public class Account {
private int balance = 0;
public void deposit(String message, int amount) {
int bal = getBalance() ;
setBalance(bal+ amount);
System.out.println(message + " Now Balance is " +
getBalance());
}
public int getBalance() {
try {
Thread.sleep(200); // Simulate Database Operation
} catch (InterruptedException e) {}
return balance;
}
www.SunilOS.com 45
Account
public void setBalance(int balance) {
try {
Thread.sleep(200); // Simulate Database Operation
} catch (InterruptedException e) {}
this.balance = balance;
}
}
www.SunilOS.com 46
RacingCondThread
public class RacingCondThread extends Thread {
public static Account data = new Account();
String name = null;
public RacingCondThread(String name) {
this.name = name;
}
public void run() {
for(int i=0;i<5;i++){
data.deposit(name, 1000);
}
}
www.SunilOS.com 47
RacingCondThread
public static void main(String[] args) {
RacingCondThread t1 = new RacingCondThread(“Raina");
RacingCondThread t2 = new RacingCondThread(“Virat");
t1.start();
t2.start();
}
www.SunilOS.com 48
Account - synchronized
public class Account {
private int balance = 0;
public synchronized void deposit(String message, int
amount) {
int bal =getBalance() + amount;
setBalance(getBalance() + amount);
System.out.println(message + " Now Bal is " + bal);
}
//…
}
www.SunilOS.com 49
Monitor Keys
Static Sync Methods
x
zy
Instance Sync Methods
a
cb
Thread1
Thread2
x() Class
Monitor
y()
a() Object
Monitor
b()
CLASS
www.SunilOS.com 50
Synchronization types
Method
public synchronized void deposit(String message, int
amount) {….
Block
public void deposit(String message, int amount) {
synchronized (this){
int bal = getBalance() + amount;
setBalance(bal);
}
System.out.println(message + " Now Bal is " + bal);
}
www.SunilOS.com 51
Monitors
Each object has a “monitor” that is a token used to
determine which application thread has control of a
particular object.
Access to the object monitor is queued.
There are two monitors:
o One for synchronized instance methods called Object
Monitor.
o Other for synchronized static methods called Class
Monitor.
Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 52
Thank You!
www.SunilOS.com 53
www.SunilOS.com

More Related Content

What's hot

Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in JavaOblivionWalker
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 

What's hot (20)

Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Collection v3
Collection v3Collection v3
Collection v3
 
Log4 J
Log4 JLog4 J
Log4 J
 
JDBC
JDBCJDBC
JDBC
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
Hibernate
Hibernate Hibernate
Hibernate
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java IO
Java IOJava IO
Java IO
 
Java I/O
Java I/OJava I/O
Java I/O
 
javathreads
javathreadsjavathreads
javathreads
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 

Viewers also liked

Viewers also liked (16)

C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
java-thread
java-threadjava-thread
java-thread
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C# Basics
C# BasicsC# Basics
C# Basics
 
C++ oop
C++ oopC++ oop
C++ oop
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
C Basics
C BasicsC Basics
C Basics
 
C++
C++C++
C++
 
37 Java Interview Questions
37 Java Interview Questions37 Java Interview Questions
37 Java Interview Questions
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 

Similar to Java Threads and Concurrency

Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfGouthamSoma1
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threadsrchakra
 

Similar to Java Threads and Concurrency (20)

Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Threads v3
Threads v3Threads v3
Threads v3
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Java
JavaJava
Java
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
multithreading
multithreadingmultithreading
multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Threads
ThreadsThreads
Threads
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Threads
ThreadsThreads
Threads
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 

More from Sunil OS

Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 

More from Sunil OS (11)

DJango
DJangoDJango
DJango
 
PDBC
PDBCPDBC
PDBC
 
OOP v3
OOP v3OOP v3
OOP v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 

Recently uploaded

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

Java Threads and Concurrency

  • 2. www.SunilOS.com 2 Process A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Most implementations of the Java virtual machine run as a single process.
  • 3. www.SunilOS.com 3 Concurrency vs. Parallelism CPU CPU1 CPU2
  • 4. www.SunilOS.com 4 Thread Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads exist within a process — every process (application) has at least one thread. Threads share the process's resources, including memory and open files. Each thread is associated with an instance of the class java.lang.Thread.
  • 6. www.SunilOS.com 6 Multitasking & Multithreading  Multitasking refers to a computer's ability to perform multiple jobs concurrently. Multitasking means more than one programs are running together on a single machine.  A thread is a single sequence of execution within a program.  Multithreading refers to multiple threads of control within a single program. Each program can run multiple threads of control within it, e.g., Web Browser.
  • 7. www.SunilOS.com 7 HelloWithoutThread public class HelloWithoutThread { String name = null; // Keeps Thread Name public HelloWithoutThread(String threadName) {// Constructor name = threadName; } public void run() { for (int i = 0; i < 50; i++) { System.out.println(i + " Hello Thread " + name); } } }
  • 8. www.SunilOS.com 8 TestWithoutThread public static void main(String[] args) { HelloWithoutThread t1 = new HelloWithoutThread(“Raina"); HelloWithoutThread t2 = new HelloWithoutThread(“Virat"); t1.run(); t2.run(); }
  • 9. www.SunilOS.com 9 TestWithoutThread Output  0 Hello Raina  1 Hello Raina  2 Hello Raina  …..  48 Hello Raina  49 Hello Raina  0 Hello Virat  1 Hello Virat  2 Hello Virat  ……..  48 Hello Virat  49 Hello Virat
  • 11. Raktabija  Raktabija had a capability to create another Raktbija by his single drop of blood.  Created Raktabija will be equally powerful, and can consume same kind of resources and work concurrently.  If one Raktabija dies another will remain active and live.  Likewise a Thread can create another thread.  Created threads will be equally powerful.  Threads need same kind of resources to be executed.  Threads work concurrently.  If one thread dies, other will remain active in memory. www.SunilOS.com 11 http://en.wikipedia.org/wiki/Raktavija
  • 12. www.SunilOS.com 12 Creating Threads  There are two ways to create a Thread object 1. Inherit Thread class. 2. Implement the Runnable.  In both cases the run() method should be implemented
  • 13. www.SunilOS.com 13 HelloWithThread public class HelloWithThread extends Thread { private String name = null; public HelloWithThread(String threadName) { name = threadName; } public void run() { for (int i = 0; i < 500; i++) { System.out.println(i + " Hello Thread " + name); } } }
  • 14. www.SunilOS.com 14 TestWithThread public static void main(String[] args) { HelloWithThread t1 = new HelloWithThread(“Raina"); HelloWithThread t2 = new HelloWithThread(“Virat"); t1.start(); t2.start(); for (int i = 0; i < 500; i++) { System.out.println(" Main Thread "); } }
  • 15. www.SunilOS.com 15 TestWithThread Output  0 Hello Thread Raina  1 Hello Thread Raina  2 Hello Thread Raina  0 Hello Thread Virat  1 Hello Thread Virat  1 Hello Thread main  2 Hello Thread main  3 Hello Thread main  3 Hello Thread Raina  4 Hello Thread Raina  2 Hello Thread Virat  3 Hello Thread Virat  4 Hello Thread main  ……..  48 Hello Thread Raina  49 Hello Thread Raina  48 Hello Thread Virat
  • 16. www.SunilOS.com 16 Scheduling Threads I/O operation completes start() Currently executed thread Ready queue •Waiting for I/O operation to be completed •Waiting to be notified •Sleeping •Waiting to enter a synchronized section Newly created threads What happens when a program with a ServerSocket calls accept()?
  • 17. www.SunilOS.com 17 Thread State Diagram Alive New Thread Dead Thread Running Runnable new ThreadExample(); run() method returns while (…) { … } Blocked Object.wait() Thread.sleep() blocking IO call waiting on a monitor thread.start();
  • 18. www.SunilOS.com 18 Thread Lifecycle Born Blocked Runnable Dead stop() start() stop() Active block on I/O I/O available JVM sleep(500) wake up suspend() resume() wait notify
  • 19. www.SunilOS.com 19 Child of other Class -Runnable Interface If a class is child of another class and you want to make it Thread then use Runnable interface since Java does not support multiple inheritance. public class HelloThread extends Hello implements Runnable { public void run() { System.out.println("Hello from Thread!"); } public static void main(String args[]) { HelloThread runThread = new HelloThread () Thread th =new Thread(runThread); th.start(); } }
  • 20. www.SunilOS.com 20 Thread Methods void start() o Creates a new thread and makes it runnable. o This method can be called only once. void run() o The new thread begins its life inside this method. void stop() (deprecated) o The thread is being terminated.
  • 21. www.SunilOS.com 21 Thread Methods yield() o Pauses the currently executing thread object and allows other thread of same priority to be executed. sleep(int m)/sleep(int m,int n)   o The thread is slept for m milliseconds and n nanoseconds.
  • 22. www.SunilOS.com 22 Multiple Threads in an Application Each thread has its private run-time stack. If two threads execute the same method, each will have its own copy of the local variables the methods uses. However, all threads see the same dynamic memory (heap). Two different threads can act on the same object and same static fields concurrently.
  • 23. www.SunilOS.com 23 Green Thread  Native Thread model: o the threads are scheduled by the OS o maps a single Java thread to an OS thread  Green Thread model: o the threads are scheduled by the Virtual Machine. o threads are invisible to the OS. o Green threads emulate multithreaded environments without relying on any native OS capabilities. o They run code in user space that manages and schedules threads o Green threads enables Java to work in environments that do not have native thread support. o OS doesn't know anything about the threads used in the VM. It's up to the VM to handle all the details.
  • 24. www.SunilOS.com 24 Scheduling Thread-scheduling is the mechanism used to determine how runnable threads are allocated CPU time. A thread-scheduling mechanism is either preemptive or non-preemptive .
  • 25. www.SunilOS.com 25 Preemptive Scheduling Preemptive scheduling – the thread scheduler preempts (pauses) a running thread and executes other thread as per schedule. Non-preemptive scheduling – the scheduler never interrupts a running thread. Other thread will get chance only if current thread dies. The non-preemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute.
  • 26. www.SunilOS.com 26 Starvation and Livelock A non-preemptive scheduler may cause starvation. Runnable threads which are in ready queue may have to wait to be executed for a very log time or forever. Sometimes, starvation is also called a livelock.
  • 27. www.SunilOS.com 27 Time-sliced Scheduling  Time-sliced scheduling – the scheduler allocates a period of time that each thread can use the CPU. When that amount of time has elapsed, the scheduler preempts the thread and switches to other thread.  Non time-sliced scheduler – the scheduler does not use elapsed time to determine when to preempt a thread. It uses other criteria such as priority or I/O status.
  • 28. www.SunilOS.com 28 Java Scheduling Java-scheduler is preemptive and based on priority of threads. It uses fixed-priority scheduling. Threads are scheduled according to their priority with respect to other threads in the ready queue.
  • 29. www.SunilOS.com 29 Java Scheduling The highest priority runnable thread is always selected for execution above lower priority threads. When multiple threads have equally high priority then only one of them will be guaranteed to be executed. Java threads are guaranteed to be preemptive-but not time sliced.
  • 30. www.SunilOS.com 30 Thread Priority Every thread has a priority. When a thread is created, it inherits the priority of the thread that created it. The priority values range from 1 to 10, in increasing priority. That means 1 is lowest and 10 is highest.
  • 31. www.SunilOS.com 31 Thread Priority (cont.) The priority can be adjusted subsequently using the setPriority(5) method. The priority of a thread may be obtained using getPriority().  Priority constants are defined in Thread class: o MIN_PRIORITY=1 o MAX_PRIORITY=10 o NORM_PRIORITY=5 Thread th = new Thread(“Raina”); o th.setPriority(4);
  • 32. www.SunilOS.com 32 Some Notes Thread implementation in Java is actually based on operating system support. Some Windows operating systems support only 7 priority levels, so different levels in Java may actually be mapped to the same operating system level.
  • 33. www.SunilOS.com 33 Daemon Threads Daemon threads are “background” threads, that provide services to other threads, e.g., the garbage collection thread. The Java VM will not exit if non-Daemon threads are executing. The Java VM will exit if only Daemon threads are executing. Daemon threads will die when the Java VM exits. t.setDaemon(true)
  • 34. www.SunilOS.com 34 ThreadGroup The ThreadGroup class is used to create groups of similar threads.
  • 35. www.SunilOS.com 35 ThreadInfo public class ThreadInfo { public static void main(String[] args) { Thread t = new Thread("My Thread"); log(" ",t); } public static void log(String indent, Thread t) { System.out.println(indent + "THREAD Name :" + t.getName()); System.out.println(indent + "ID :" + t.getId()); System.out.println(indent + "Priority :" + t.getPriority()); System.out.println(indent + "State :" + t.getState()); System.out.println(indent + "Thread Group :" + t.getThreadGroup().getName()); System.out.println(indent + "Is Alive :" + t.isAlive()); System.out.println(indent + "Is Daemon :" + t.isDaemon() + "n"); } }
  • 36. www.SunilOS.com 36 ThreadInfo (Cont..) public static void info(String indent, ThreadGroup tg) { int threadCount = tg.activeCount(); //Get Active Thread Count Thread[] threads = new Thread[threadCount]; tg.enumerate(threads); //Get Active Threads System.out.println(indent + "THREAD GROUP NAME: " + tg.getName()); System.out.println(indent + "Is Daemon : " + tg.isDaemon()); //Log Threads Details for (int i = 0; i < threads.length; i++) { log( indent + "t" , threads[i]); } int groupCount = tg.activeGroupCount();//Get Active ThreadGroup Count ThreadGroup[] groups = new ThreadGroup[groupCount]; tg.enumerate(groups); //Get ThreadGroups for (int i = 0; i < groups.length; i++) { info(indent + "t", groups[i]); } }
  • 37. www.SunilOS.com 37 ThreadInfo (Cont..) public static void main(String[] args) throws Exception{ Thread t = Thread.currentThread(); //Get Currect Thread ThreadGroup tg = t.getThreadGroup(); while(tg.getParent() !=null){ //Get Root ThreadGroup tg=tg.getParent() ; } HelloWithThread t1 = new HelloWithThread("TRaina"); t1.setPriority(1); HelloWithThread t2 = new HelloWithThread("Yuvraj"); t2.setPriority(1); t1.start(); t2.start(); info("", tg); }
  • 38. www.SunilOS.com 38 Concurrency An object in a program can be changed by more than one threads concurrently. Q: Is the order of changes that were preformed on the object important?
  • 40. www.SunilOS.com 40 Race Condition When two threads are simultaneously modifying a single object, is called race- condition. Both threads “race” to store their values in a single object. The outcome of a program is affected by the order in which the program's threads are allocated CPU time.
  • 41. www.SunilOS.com 41 Deposit in an Account Account User1 User2 Balance = 1000 Balance = 2000 getBalance():1000 setBalance(2000) setBalance(2000) getBalance():1000
  • 42. www.SunilOS.com 42 Synchronized access AccountUser1 User2 Balance = 1000 Balance = 3000 getBalance():1000 setBalance(2000) setBalance(3000) getBalance():2000 Deposit in an Account
  • 43. www.SunilOS.com 43 Instance vs static attributes instance static instance static Attributes Methods Person -name : String -address: String $ AVR_AGE : int = 60 +getName() +getAddress() $ getAveAge() +getName() +getAddress() $ getAveAge() AVR_AGE = 60 Person p1, p2 p1 = new Person() p2 = new Person() Name = A Address = Add1 Name = B Address = Add2 p1 p2p1.getName () P2.getAvrAge() Person.getAvrAge() Class 1011 1010 1010 1011 2B 2B
  • 44. www.SunilOS.com 44 Account public class Account { private int balance = 0; public void deposit(String message, int amount) { int bal = getBalance() ; setBalance(bal+ amount); System.out.println(message + " Now Balance is " + getBalance()); } public int getBalance() { try { Thread.sleep(200); // Simulate Database Operation } catch (InterruptedException e) {} return balance; }
  • 45. www.SunilOS.com 45 Account public void setBalance(int balance) { try { Thread.sleep(200); // Simulate Database Operation } catch (InterruptedException e) {} this.balance = balance; } }
  • 46. www.SunilOS.com 46 RacingCondThread public class RacingCondThread extends Thread { public static Account data = new Account(); String name = null; public RacingCondThread(String name) { this.name = name; } public void run() { for(int i=0;i<5;i++){ data.deposit(name, 1000); } }
  • 47. www.SunilOS.com 47 RacingCondThread public static void main(String[] args) { RacingCondThread t1 = new RacingCondThread(“Raina"); RacingCondThread t2 = new RacingCondThread(“Virat"); t1.start(); t2.start(); }
  • 48. www.SunilOS.com 48 Account - synchronized public class Account { private int balance = 0; public synchronized void deposit(String message, int amount) { int bal =getBalance() + amount; setBalance(getBalance() + amount); System.out.println(message + " Now Bal is " + bal); } //… }
  • 49. www.SunilOS.com 49 Monitor Keys Static Sync Methods x zy Instance Sync Methods a cb Thread1 Thread2 x() Class Monitor y() a() Object Monitor b() CLASS
  • 50. www.SunilOS.com 50 Synchronization types Method public synchronized void deposit(String message, int amount) {…. Block public void deposit(String message, int amount) { synchronized (this){ int bal = getBalance() + amount; setBalance(bal); } System.out.println(message + " Now Bal is " + bal); }
  • 51. www.SunilOS.com 51 Monitors Each object has a “monitor” that is a token used to determine which application thread has control of a particular object. Access to the object monitor is queued. There are two monitors: o One for synchronized instance methods called Object Monitor. o Other for synchronized static methods called Class Monitor.
  • 52. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 52