SlideShare a Scribd company logo
1 of 37
www.SunilOS.com 1
www.sunilos.com
www.raystec.com
Concurrency/Threads
Mother’s morning
www.SunilOS.com 2
Concurrency & Threads
1:
2:
3:
4:
6:
single threading
multi threading
1
Threading
www.SunilOS.com 3
Single Threading Multithreading
Thread
Thread
Thread
Thread
Thread
OS
OS
www.SunilOS.com 4
OS
CPU Cycle
Thread
Thread
Thread
Thread
Thread
Thread
Thread
HelloNoThread
1. public class HelloNoThread {
2. String name = null;
3. public HelloNoThread(String n) {
4. name = n;
5. }
6. public void run() {
7. for (int i = 0; i < 50; i++) {
8. System.out.println(i + name);
9. }
10. }
11.}
www.SunilOS.com 5
TestHelloNoThread
1. public class TestHelloNoThread {
2. public static void main(String[] args) {
3. HelloNoThread t1 = new HelloNoThread("Ram");
4. HelloNoThread t2 = new HelloNoThread("Shyam");
5. t1.run();
6. t2.run();
7. }
8. }
 0 Ram
 1 Ram
 2 Ram
 …..
 48 Ram
 49 Ram
 0 Shyam
 1 Shyam
 2 Shyam
 ……..
 48 Shyam
 49 Shyam
www.SunilOS.com 6
t1.run() t2.run()
Create Thread
www.SunilOS.com 7
Thread
+run()
+start()
+sleep()
MyThread HelloThread Other
+run() +run() +run()
extends
HelloThread
1. public class HelloThread extends Thread{
2. String name = null;
3. public HelloThread(String n) {
4. name = n;
5. }
6. public void run() {
7. for (int i = 0; i < 50; i++) {
8. System.out.println(i + name);
9. }
10. }
11.}
www.SunilOS.com 8
TestHelloThread
1. public class TestHelloThread{
2. public static void main(String[] args) {
3. HelloThread t1 = new HelloThread("Ram");
4. HelloThread t2 = new HelloThread("Shyam");
5. t1.start();
6. t2.start();
7. for (int i = 0; i < 50; i++) {
8. System.out.println(“main");
9. }
10. }
11.}
 0 Ram
 1 Ram
 2 Ram
 0 Shyam
 1 Shyam
 1 main
 2 main
 3 main
 3 Ram
 4 Ram
 2 Shyam
 3 Shyam
 4 main
 ……..
 48 Ram
 49 Ram
 48 Shyam
www.SunilOS.com 9
CPU Scheduling
CPU
Main
Ram
Shyam
T1 T2 T3
Pani puri –Thread scheduling
www.SunilOS.com 11
OS
CPU Cycle
Ready Thread Queue
Thread
Thread Thread Thread
Thread
Thread Priority
www.SunilOS.com 12
Priority range from 1-10
www.SunilOS.com 13
CPU Cycle
Priority
www.SunilOS.com 14
Set and get priority
 Thread t = new Thread(“Ram”);
o t.setPriority(9);
o int i = t.getPriority();
 Default priority is 5
 Priority constants are defined in Thread class:
o Thread.MIN_PRIORITY=1
o Thread.MAX_PRIORITY=10
o Thread.NORM_PRIORITY=5
Runnable interface
www.SunilOS.com 15
Runnable
+run()
Implements
ParentClass
extends
ChildClass
+run()
Runnable interface
1. public class HelloRunnable implements Runnable {
2. String name = null;
3. public HelloRunnable(String n) {
4. name = n;
5. }
6. public void run() {
7. for (int i = 0; i < 50; i++) {
8. System.out.println(i + name);
9. }
10. }
11.}
www.SunilOS.com 16
Test Runnable
 public class TestHelloRunnable {
 public static void main(String[] args) {
 Thread t1 = new Thread(new HelloRunnable("Ram"));
 Thread t2 = new Thread(new HelloRunnable("Shyam"));
 t1.start();
 t2.start();
 for (int i = 0; i < 500; i++) {
 System.out.println("Main");
 }
 }
 } www.SunilOS.com 17
www.SunilOS.com 18
Threads and Processes
Thread creation
A java program executed as thread inside JVM
A thread can create another thread.
Threads work concurrently.
If one thread dies, other will remain active in
memory
www.SunilOS.com 19
www.SunilOS.com 20
Thread Lifecycle - States
2: start()
finish run()
1: new
Born Blocked
Runnable
Dead
1. I/O available
2. notify()
3. wake up()
1. block on I/O
2. wait()
3. sleep()
www.SunilOS.com 21
Thread Methods
 start()
o Starts the thread and put into runnable queue
 run()
o Performs operation
 Thread.sleep(int m)/sleep(int m,int n)
o Sleeps the thread for given time in milliseconds and nanoseconds
 Thread.yield()
o Pauses currently executing thread and put at last in the runnable queue
www.SunilOS.com 22
Daemon Threads
 Daemon threads are supporting and background threads
 It provides services to normal threads
 Garbage Collector is a Daemon thread.
 t.setDaemon(true)
Daemon
Thread
Normal
Thread
Usage | multi user system
www.SunilOS.com 23
Web Application
Database
Race condition
www.SunilOS.com 24
Thread 1
Thread 2
Object
www.SunilOS.com 25
Race Condition
 Threads of a process can share common memory area
 When two threads simultaneously try to access and modify an
object, it is called race-condition
 The result of a program is affected by the order in which threads
are allocated CPU time and executed
www.SunilOS.com 26
Deposit in the Account
Account
Balance = 1000
Balance = 2000
getBalance():1000
setBalance(2000)
setBalance(2000)
getBalance():1000
getBalance()
CPU
getBalance()
setBalance()
setBalance()
User1 User 2
Deposit
Deposit
www.SunilOS.com 27
Synchronized access
Account
Balance = 1000
Balance = 3000
getBalance():1000
setBalance(2000)
setBalance(3000)
getBalance():2000
User1 User 2
Deposit Deposit
getBalance()
CPU
locked
setBalance()
setBalance()
getBalance()
www.SunilOS.com 28
Account
1. public class Account {
2. private int balance = 0;
3. public int getBalance() {
4. try {
5. Thread.sleep(200);
6. } catch (InterruptedException e) {}
7. return balance;
8. }
9. public void setBalance(int balance) {
10. try {
11. Thread.sleep(200);
12. } catch (InterruptedException e) {}
13. this.balance = balance;
14. }
15.
www.SunilOS.com 29
Account
1. public synchronized void deposit(String msg, int amt) {
2. int bal = getBalance();
3. bal = bal + amt;
4. setBalance(bal);
5. System.out.println(msg + " new balance " + bal);
6. }
7. }
www.SunilOS.com 30
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 31
TestRacingCondThread
public static void main(String[] args) {
RacingCondThread t1 = new RacingCondThread(“Ram");
RacingCondThread t2 = new RacingCondThread(“Shyam");
t1.start();
t2.start();
}
Output
 void deposit(..)
o Ram balance 1000
o Shyam balance 1000
o Ram balance 2000
o Shyam balance 2000
o Shyam balance 3000
o Ram balance 3000
o Shyam balance 4000
o Ram balance 4000
o Shyam balance 5000
o Ram balance 5000
 synchronized void deposit(..)
o Ram balance 1000
o Ram balance 2000
o Ram balance 3000
o Ram balance 4000
o Ram balance 5000
o Shyam balance 6000
o Shyam balance 7000
o Shyam balance 8000
o Shyam balance 9000
o Shyam balance 10000
www.SunilOS.com 32
www.SunilOS.com 33
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 34
Monitors / Locks
 It is a lock or token of an object
 The thread has lock, can access object
 Other threads will be in waiting queue
 One object has two monitors or tokens
o One for instance methods, called Object Monitor
o Second for static methods, called Class Monitor
www.SunilOS.com 35
Monitor Keys
Static Sync Methods
x
z
y
Instance Sync Methods
a
c
b
Thread1
Thread2
x() Class
Monitor
y()
a() Object
Monitor
b()
CLASS
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 36
Thank You!
www.SunilOS.com 37
www.SunilOS.com

More Related Content

What's hot

Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 

What's hot (20)

Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Log4 J
Log4 JLog4 J
Log4 J
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
DJango
DJangoDJango
DJango
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
C++
C++C++
C++
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
PDBC
PDBCPDBC
PDBC
 

Similar to Threads V4

JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdfMohit Kumar
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 25 of 180
The Ring programming language version 1.5.1 book - Part 25 of 180The Ring programming language version 1.5.1 book - Part 25 of 180
The Ring programming language version 1.5.1 book - Part 25 of 180Mahmoud Samir Fayed
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی Mohammad Reza Kamalifard
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196Mahmoud Samir Fayed
 
Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 

Similar to Threads V4 (20)

JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Threads
ThreadsThreads
Threads
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
The Ring programming language version 1.5.1 book - Part 25 of 180
The Ring programming language version 1.5.1 book - Part 25 of 180The Ring programming language version 1.5.1 book - Part 25 of 180
The Ring programming language version 1.5.1 book - Part 25 of 180
 
Threads
ThreadsThreads
Threads
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196
 
Threads v3
Threads v3Threads v3
Threads v3
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 

More from Sunil OS

Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 

More from Sunil OS (10)

OOP v3
OOP v3OOP v3
OOP v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++ oop
C++ oopC++ oop
C++ oop
 
C Basics
C BasicsC Basics
C Basics
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
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 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .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"
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
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
 

Threads V4

  • 2. Mother’s morning www.SunilOS.com 2 Concurrency & Threads 1: 2: 3: 4: 6: single threading multi threading 1
  • 3. Threading www.SunilOS.com 3 Single Threading Multithreading Thread Thread Thread Thread Thread OS OS
  • 5. HelloNoThread 1. public class HelloNoThread { 2. String name = null; 3. public HelloNoThread(String n) { 4. name = n; 5. } 6. public void run() { 7. for (int i = 0; i < 50; i++) { 8. System.out.println(i + name); 9. } 10. } 11.} www.SunilOS.com 5
  • 6. TestHelloNoThread 1. public class TestHelloNoThread { 2. public static void main(String[] args) { 3. HelloNoThread t1 = new HelloNoThread("Ram"); 4. HelloNoThread t2 = new HelloNoThread("Shyam"); 5. t1.run(); 6. t2.run(); 7. } 8. }  0 Ram  1 Ram  2 Ram  …..  48 Ram  49 Ram  0 Shyam  1 Shyam  2 Shyam  ……..  48 Shyam  49 Shyam www.SunilOS.com 6 t1.run() t2.run()
  • 7. Create Thread www.SunilOS.com 7 Thread +run() +start() +sleep() MyThread HelloThread Other +run() +run() +run() extends
  • 8. HelloThread 1. public class HelloThread extends Thread{ 2. String name = null; 3. public HelloThread(String n) { 4. name = n; 5. } 6. public void run() { 7. for (int i = 0; i < 50; i++) { 8. System.out.println(i + name); 9. } 10. } 11.} www.SunilOS.com 8
  • 9. TestHelloThread 1. public class TestHelloThread{ 2. public static void main(String[] args) { 3. HelloThread t1 = new HelloThread("Ram"); 4. HelloThread t2 = new HelloThread("Shyam"); 5. t1.start(); 6. t2.start(); 7. for (int i = 0; i < 50; i++) { 8. System.out.println(“main"); 9. } 10. } 11.}  0 Ram  1 Ram  2 Ram  0 Shyam  1 Shyam  1 main  2 main  3 main  3 Ram  4 Ram  2 Shyam  3 Shyam  4 main  ……..  48 Ram  49 Ram  48 Shyam www.SunilOS.com 9
  • 11. Pani puri –Thread scheduling www.SunilOS.com 11 OS CPU Cycle Ready Thread Queue Thread Thread Thread Thread Thread
  • 13. Priority range from 1-10 www.SunilOS.com 13 CPU Cycle Priority
  • 14. www.SunilOS.com 14 Set and get priority  Thread t = new Thread(“Ram”); o t.setPriority(9); o int i = t.getPriority();  Default priority is 5  Priority constants are defined in Thread class: o Thread.MIN_PRIORITY=1 o Thread.MAX_PRIORITY=10 o Thread.NORM_PRIORITY=5
  • 16. Runnable interface 1. public class HelloRunnable implements Runnable { 2. String name = null; 3. public HelloRunnable(String n) { 4. name = n; 5. } 6. public void run() { 7. for (int i = 0; i < 50; i++) { 8. System.out.println(i + name); 9. } 10. } 11.} www.SunilOS.com 16
  • 17. Test Runnable  public class TestHelloRunnable {  public static void main(String[] args) {  Thread t1 = new Thread(new HelloRunnable("Ram"));  Thread t2 = new Thread(new HelloRunnable("Shyam"));  t1.start();  t2.start();  for (int i = 0; i < 500; i++) {  System.out.println("Main");  }  }  } www.SunilOS.com 17
  • 19. Thread creation A java program executed as thread inside JVM A thread can create another thread. Threads work concurrently. If one thread dies, other will remain active in memory www.SunilOS.com 19
  • 20. www.SunilOS.com 20 Thread Lifecycle - States 2: start() finish run() 1: new Born Blocked Runnable Dead 1. I/O available 2. notify() 3. wake up() 1. block on I/O 2. wait() 3. sleep()
  • 21. www.SunilOS.com 21 Thread Methods  start() o Starts the thread and put into runnable queue  run() o Performs operation  Thread.sleep(int m)/sleep(int m,int n) o Sleeps the thread for given time in milliseconds and nanoseconds  Thread.yield() o Pauses currently executing thread and put at last in the runnable queue
  • 22. www.SunilOS.com 22 Daemon Threads  Daemon threads are supporting and background threads  It provides services to normal threads  Garbage Collector is a Daemon thread.  t.setDaemon(true) Daemon Thread Normal Thread
  • 23. Usage | multi user system www.SunilOS.com 23 Web Application Database
  • 25. www.SunilOS.com 25 Race Condition  Threads of a process can share common memory area  When two threads simultaneously try to access and modify an object, it is called race-condition  The result of a program is affected by the order in which threads are allocated CPU time and executed
  • 26. www.SunilOS.com 26 Deposit in the Account Account Balance = 1000 Balance = 2000 getBalance():1000 setBalance(2000) setBalance(2000) getBalance():1000 getBalance() CPU getBalance() setBalance() setBalance() User1 User 2 Deposit Deposit
  • 27. www.SunilOS.com 27 Synchronized access Account Balance = 1000 Balance = 3000 getBalance():1000 setBalance(2000) setBalance(3000) getBalance():2000 User1 User 2 Deposit Deposit getBalance() CPU locked setBalance() setBalance() getBalance()
  • 28. www.SunilOS.com 28 Account 1. public class Account { 2. private int balance = 0; 3. public int getBalance() { 4. try { 5. Thread.sleep(200); 6. } catch (InterruptedException e) {} 7. return balance; 8. } 9. public void setBalance(int balance) { 10. try { 11. Thread.sleep(200); 12. } catch (InterruptedException e) {} 13. this.balance = balance; 14. } 15.
  • 29. www.SunilOS.com 29 Account 1. public synchronized void deposit(String msg, int amt) { 2. int bal = getBalance(); 3. bal = bal + amt; 4. setBalance(bal); 5. System.out.println(msg + " new balance " + bal); 6. } 7. }
  • 30. www.SunilOS.com 30 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); } }
  • 31. www.SunilOS.com 31 TestRacingCondThread public static void main(String[] args) { RacingCondThread t1 = new RacingCondThread(“Ram"); RacingCondThread t2 = new RacingCondThread(“Shyam"); t1.start(); t2.start(); }
  • 32. Output  void deposit(..) o Ram balance 1000 o Shyam balance 1000 o Ram balance 2000 o Shyam balance 2000 o Shyam balance 3000 o Ram balance 3000 o Shyam balance 4000 o Ram balance 4000 o Shyam balance 5000 o Ram balance 5000  synchronized void deposit(..) o Ram balance 1000 o Ram balance 2000 o Ram balance 3000 o Ram balance 4000 o Ram balance 5000 o Shyam balance 6000 o Shyam balance 7000 o Shyam balance 8000 o Shyam balance 9000 o Shyam balance 10000 www.SunilOS.com 32
  • 33. www.SunilOS.com 33 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); }
  • 34. www.SunilOS.com 34 Monitors / Locks  It is a lock or token of an object  The thread has lock, can access object  Other threads will be in waiting queue  One object has two monitors or tokens o One for instance methods, called Object Monitor o Second for static methods, called Class Monitor
  • 35. www.SunilOS.com 35 Monitor Keys Static Sync Methods x z y Instance Sync Methods a c b Thread1 Thread2 x() Class Monitor y() a() Object Monitor b() CLASS
  • 36. 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 36

Editor's Notes

  1. www.sunilos.com
  2. Cell- 92292 60504
  3. Cell- 92292 60504
  4. Cell- 92292 60504
  5. Cell- 92292 60504
  6. Cell- 92292 60504
  7. Cell- 92292 60504
  8. Cell- 92292 60504
  9. Cell- 92292 60504
  10. Cell- 92292 60504
  11. Cell- 92292 60504
  12. Cell- 92292 60504
  13. Cell- 92292 60504
  14. Cell- 92292 60504
  15. Cell- 92292 60504
  16. Cell- 92292 60504
  17. Cell- 92292 60504
  18. Cell- 92292 60504
  19. Cell- 92292 60504
  20. Cell- 92292 60504
  21. Cell- 92292 60504