SlideShare a Scribd company logo
Multithreading in Java
Fawzi Emad
Chau-Wen Tseng
Department of Computer Science
University of Maryland, College Park
Problem
Multiple tasks for computer
Draw & display images on screen
Check keyboard & mouse input
Send & receive data on network
Read & write files to disk
Perform useful computation (editor, browser, game)
How does computer do everything at once?
Multitasking
Multiprocessing
Multitasking (Time-Sharing)
Approach
Computer does some work on a task
Computer then quickly switch to next task
Tasks managed by operating system (scheduler)
Computer seems to work on tasks concurrently
Can improve performance by reducing waiting
Multitasking Can Aid Performance
Single task
Two tasks
Multiprocessing (Multithreading)
Approach
Multiple processing units (multiprocessor)
Computer works on several tasks in parallel
Performance can be improved
4096 processor
Cray X1
32 processor
Pentium Xeon
Dual-core AMD
Athlon X2
Perform Multiple Tasks Using…
1. Process
Definition – executable program loaded in memory
Has own address space
Variables & data structures (in memory)
Each process may execute a different program
Communicate via operating system, files, network
May contain multiple threads
Perform Multiple Tasks Using…
2. Thread
Definition – sequentially executed stream of
instructions
Shares address space with other threads
Has own execution context
Program counter, call stack (local variables)
Communicate via shared access to data
Multiple threads in process execute same program
Also known as “lightweight process”
Motivation for Multithreading
1. Captures logical structure of problem
May have concurrent interacting components
Can handle each component using separate thread
Simplifies programming for problem
Example
Web Server uses
threads to handle …
Multiple simultaneous
web browser requests
Motivation for Multithreading
2. Better utilize hardware resources
When a thread is delayed, compute other threads
Given extra hardware, compute threads in parallel
Reduce overall execution time
Example
Multiple simultaneous
web browser requests…
Handled faster by
multiple web servers
Multithreading Overview
Motivation & background
Threads
Creating Java threads
Thread states
Scheduling
Synchronization
Data races
Locks
Wait / Notify
Programming with Threads
Concurrent programming
Writing programs divided into independent tasks
Tasks may be executed in parallel on multiprocessors
Multithreading
Executing program with multiple threads in parallel
Special form of multiprocessing
Creating Threads in Java
Two approaches
Thread class
public class Thread extends Object { … }
Runnable interface
public interface Runnable {
public void run(); // work  thread
}
Thread Class
public class Thread extends Object
implements Runnable {
public Thread();
public Thread(String name); // Thread name
public Thread(Runnable R); // Thread  R.run()
public Thread(Runnable R, String name);
public void run(); // if no R, work for thread
public void start();// begin thread execution
...
}
More Thread Class Methods
public class Thread extends Object {
…
public static Thread currentThread()
public String getName()
public void interrupt()
public boolean isAlive()
public void join()
public void setDaemon()
public void setName()
public void setPriority()
public static void sleep()
public static void yield()
}
Creating Threads in Java
1. Thread class
Extend Thread class and override the run method
Example
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT T = new MyT () ; // create thread
T.start(); // begin running thread
… // thread executing in
parallel
Creating Threads in Java
2. Runnable interface
Create object implementing Runnable interface
Pass it to Thread object via Thread constructor
Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread T = new Thread(new MyT); // create thread
T.start(); // begin running thread
… // thread executing in parallel
Creating Threads in Java
Note
Thread starts executing only if start() is called
Runnable is interface
So it can be multiply inherited
Required for multithreading in applets
Threads – Thread States
Java thread can be in one of these states
New – thread allocated & waiting for start()
Runnable – thread can begin execution
Running – thread currently executing
Blocked – thread waiting for event (I/O, etc.)
Dead – thread finished
Transitions between states caused by
Invoking methods in class Thread
new(), start(), yield(), sleep(), wait(), notify()…
Other (external) events
Scheduler, I/O, returning from run()…
Threads – Thread States
State diagram
runnable
scheduler
new
dead
running blocked
new start
terminate
IO, sleep,
wait, join
yield,
time
slice
notify, notifyAll,
IO complete,
sleep expired,
join complete
Daemon Threads
Java threads types
User
Daemon
Provide general services
Typically never terminate
Call setDaemon() before start()
Program termination
1. All user threads finish
2. Daemon threads are terminated by JVM
3. Main program finishes
Threads – Scheduling
Scheduler
Determines which runnable threads to run
Can be based on thread priority
Part of OS or Java Virtual Machine (JVM)
Scheduling policy
Nonpreemptive (cooperative) scheduling
Preemptive scheduling
Threads – Non-preemptive Scheduling
Threads continue execution until
Thread terminates
Executes instruction causing wait (e.g., IO)
Thread volunteering to stop (invoking yield or sleep)
Threads – Preemptive Scheduling
Threads continue execution until
Same reasons as non-preemptive scheduling
Preempted by scheduler
Java Thread Example
public class ThreadExample extends Thread {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
try {
sleep((int)(Math.random() * 5000)); // 5 secs
} catch (InterruptedException e) { }
}
public static void main(String[] args) {
new ThreadExample().start();
new ThreadExample().start();
System.out.println("Done");
}
}
Java Thread Example – Output
Possible outputs
0,1,2,0,1,2,Done // thread 1, thread 2, main()
0,1,2,Done,0,1,2 // thread 1, main(), thread 2
Done,0,1,2,0,1,2 // main(), thread 1, thread 2
0,0,1,1,2,Done,2 // main() & threads interleaved
thread 1: println 0, println 1, println 2
main (): thread 1, thread 2, println Done
thread 2: println 0, println 1, println 2
Data Races
public class DataRace extends Thread {
static int x;
public void run() {
for (int i = 0; i < 100000; i++) {
x = x + 1;
x = x – 1;
}
}
public static void main(String[] args) {
x = 0;
for (int i = 0; i < 100000; i++)
new DataRace().start();
System.out.println(x);// x not always 0!
}
}
Thread Scheduling Observations
Order thread is selected is indeterminate
Depends on scheduler
Thread can block indefinitely (starvation)
If other threads always execute first
Thread scheduling may cause data races
Modifying same data from multiple threads
Result depends on thread execution order
Synchronization
Control thread execution order
Eliminate data races
Ad

More Related Content

Similar to Advanced Java Programming for Beginners. (20)

Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
multhi threading concept in oops through java
multhi threading concept in oops through javamulthi threading concept in oops through java
multhi threading concept in oops through java
Parameshwar Maddela
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
HemantSharma134028
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
kavitamittal18
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
concurrency
concurrencyconcurrency
concurrency
Jonathan Wagoner
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Java Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHatJava Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
happycocoman
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
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
arnavytstudio2814
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Lecture10
Lecture10Lecture10
Lecture10
vantinhkhuc
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
Krystian Zybała
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptxmultithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
multhi threading concept in oops through java
multhi threading concept in oops through javamulthi threading concept in oops through java
multhi threading concept in oops through java
Parameshwar Maddela
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
kavitamittal18
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Java Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHatJava Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
happycocoman
 
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
arnavytstudio2814
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
Krystian Zybała
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptxmultithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 

Recently uploaded (20)

Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Lecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptxLecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptx
Arshad Shaikh
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)
GS Virdi
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Rococo versus Neoclassicism. The artistic styles of the 18th century
Rococo versus Neoclassicism. The artistic styles of the 18th centuryRococo versus Neoclassicism. The artistic styles of the 18th century
Rococo versus Neoclassicism. The artistic styles of the 18th century
Gema
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Lecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptxLecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptx
Arshad Shaikh
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)
GS Virdi
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Rococo versus Neoclassicism. The artistic styles of the 18th century
Rococo versus Neoclassicism. The artistic styles of the 18th centuryRococo versus Neoclassicism. The artistic styles of the 18th century
Rococo versus Neoclassicism. The artistic styles of the 18th century
Gema
 
Ad

Advanced Java Programming for Beginners.

  • 1. Multithreading in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park
  • 2. Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files to disk Perform useful computation (editor, browser, game) How does computer do everything at once? Multitasking Multiprocessing
  • 3. Multitasking (Time-Sharing) Approach Computer does some work on a task Computer then quickly switch to next task Tasks managed by operating system (scheduler) Computer seems to work on tasks concurrently Can improve performance by reducing waiting
  • 4. Multitasking Can Aid Performance Single task Two tasks
  • 5. Multiprocessing (Multithreading) Approach Multiple processing units (multiprocessor) Computer works on several tasks in parallel Performance can be improved 4096 processor Cray X1 32 processor Pentium Xeon Dual-core AMD Athlon X2
  • 6. Perform Multiple Tasks Using… 1. Process Definition – executable program loaded in memory Has own address space Variables & data structures (in memory) Each process may execute a different program Communicate via operating system, files, network May contain multiple threads
  • 7. Perform Multiple Tasks Using… 2. Thread Definition – sequentially executed stream of instructions Shares address space with other threads Has own execution context Program counter, call stack (local variables) Communicate via shared access to data Multiple threads in process execute same program Also known as “lightweight process”
  • 8. Motivation for Multithreading 1. Captures logical structure of problem May have concurrent interacting components Can handle each component using separate thread Simplifies programming for problem Example Web Server uses threads to handle … Multiple simultaneous web browser requests
  • 9. Motivation for Multithreading 2. Better utilize hardware resources When a thread is delayed, compute other threads Given extra hardware, compute threads in parallel Reduce overall execution time Example Multiple simultaneous web browser requests… Handled faster by multiple web servers
  • 10. Multithreading Overview Motivation & background Threads Creating Java threads Thread states Scheduling Synchronization Data races Locks Wait / Notify
  • 11. Programming with Threads Concurrent programming Writing programs divided into independent tasks Tasks may be executed in parallel on multiprocessors Multithreading Executing program with multiple threads in parallel Special form of multiprocessing
  • 12. Creating Threads in Java Two approaches Thread class public class Thread extends Object { … } Runnable interface public interface Runnable { public void run(); // work  thread }
  • 13. Thread Class public class Thread extends Object implements Runnable { public Thread(); public Thread(String name); // Thread name public Thread(Runnable R); // Thread  R.run() public Thread(Runnable R, String name); public void run(); // if no R, work for thread public void start();// begin thread execution ... }
  • 14. More Thread Class Methods public class Thread extends Object { … public static Thread currentThread() public String getName() public void interrupt() public boolean isAlive() public void join() public void setDaemon() public void setName() public void setPriority() public static void sleep() public static void yield() }
  • 15. Creating Threads in Java 1. Thread class Extend Thread class and override the run method Example public class MyT extends Thread { public void run() { … // work for thread } } MyT T = new MyT () ; // create thread T.start(); // begin running thread … // thread executing in parallel
  • 16. Creating Threads in Java 2. Runnable interface Create object implementing Runnable interface Pass it to Thread object via Thread constructor Example public class MyT implements Runnable { public void run() { … // work for thread } } Thread T = new Thread(new MyT); // create thread T.start(); // begin running thread … // thread executing in parallel
  • 17. Creating Threads in Java Note Thread starts executing only if start() is called Runnable is interface So it can be multiply inherited Required for multithreading in applets
  • 18. Threads – Thread States Java thread can be in one of these states New – thread allocated & waiting for start() Runnable – thread can begin execution Running – thread currently executing Blocked – thread waiting for event (I/O, etc.) Dead – thread finished Transitions between states caused by Invoking methods in class Thread new(), start(), yield(), sleep(), wait(), notify()… Other (external) events Scheduler, I/O, returning from run()…
  • 19. Threads – Thread States State diagram runnable scheduler new dead running blocked new start terminate IO, sleep, wait, join yield, time slice notify, notifyAll, IO complete, sleep expired, join complete
  • 20. Daemon Threads Java threads types User Daemon Provide general services Typically never terminate Call setDaemon() before start() Program termination 1. All user threads finish 2. Daemon threads are terminated by JVM 3. Main program finishes
  • 21. Threads – Scheduling Scheduler Determines which runnable threads to run Can be based on thread priority Part of OS or Java Virtual Machine (JVM) Scheduling policy Nonpreemptive (cooperative) scheduling Preemptive scheduling
  • 22. Threads – Non-preemptive Scheduling Threads continue execution until Thread terminates Executes instruction causing wait (e.g., IO) Thread volunteering to stop (invoking yield or sleep)
  • 23. Threads – Preemptive Scheduling Threads continue execution until Same reasons as non-preemptive scheduling Preempted by scheduler
  • 24. Java Thread Example public class ThreadExample extends Thread { public void run() { for (int i = 0; i < 3; i++) System.out.println(i); try { sleep((int)(Math.random() * 5000)); // 5 secs } catch (InterruptedException e) { } } public static void main(String[] args) { new ThreadExample().start(); new ThreadExample().start(); System.out.println("Done"); } }
  • 25. Java Thread Example – Output Possible outputs 0,1,2,0,1,2,Done // thread 1, thread 2, main() 0,1,2,Done,0,1,2 // thread 1, main(), thread 2 Done,0,1,2,0,1,2 // main(), thread 1, thread 2 0,0,1,1,2,Done,2 // main() & threads interleaved thread 1: println 0, println 1, println 2 main (): thread 1, thread 2, println Done thread 2: println 0, println 1, println 2
  • 26. Data Races public class DataRace extends Thread { static int x; public void run() { for (int i = 0; i < 100000; i++) { x = x + 1; x = x – 1; } } public static void main(String[] args) { x = 0; for (int i = 0; i < 100000; i++) new DataRace().start(); System.out.println(x);// x not always 0! } }
  • 27. Thread Scheduling Observations Order thread is selected is indeterminate Depends on scheduler Thread can block indefinitely (starvation) If other threads always execute first Thread scheduling may cause data races Modifying same data from multiple threads Result depends on thread execution order Synchronization Control thread execution order Eliminate data races