SlideShare a Scribd company logo
1 of 23
Multithreaded Programs in Java
Tasks and Threads
• A task is an abstraction of a series of steps
– Might be done in a separate thread
– Java libraries use the Runnable interface
– work done by method run()
• Thread: a Java class for a thread
– work done by method run()
• How to associate a task with a thread?
• How to start a thread?
Creating a Task and Thread
• Warning: old way(s), new ways
• First, if you have a thread object, you can call
start() on that object
– Makes it available to be run
– When it’s time to run it, Thread’s run() is called
• So, create a thread using “old” (not good) way
– Write class that extends Thread, e.g. MyThread
– Define your own run()
– Create a MyThread object and call start() on it
• We won’t do this! Not good design
Runnables and Thread
• Use the “task abstraction” and create a class
that implements Runnable interface
– Define the run() method to do the work you want
• Now, two ways to make your task run in a
separate thread
– Create a Thread object and pass a Runnable to the
constructor
– As before, call start() on the Thread object
Do we need a Thread “manager”?
• If your code is responsible for creating a bunch
of tasks, linking them with Threads, and
starting them all, then you have things to
worry about:
– What if you start too many threads? Can you
manage the number of running threads?
– Can you shutdown all the threads?
– If one fails, can you restart it?
Executors
• An Executor is an object that manages running
tasks
– Submit a Runnable to be run with Executor’s
execute() method
– So, instead of creating a Thread for your Runnable
and calling start() on that, do this:
• Get an Executor object, say called exec
• Create a Runnable, say called myTask
• Submit for running: exec.execute(myTask)
How to Get an Executor
• Use static methods in Executors library.
• Fixed “thread pool”: at most N threads running at
one time
Executor exec =
Executors.newFixedThreadPool(MAX_THREADS);
• Unlimited number of threads
Executor exec =
Executors.newCachedThreadPool();
Summary So Far
• Create a class that implements a Runnable to
be your “worker”
• Create Runnable objects
• Create an Executor
• Submit each Runnable to the Executor which
starts it up in a separate thread
Synchronization
• Understand the issue with concurrent access
to shared data?
– Data could be a counter (int) or a data structure
(e.g. a Map or List or Set)
• A critical section: a block of code that can
only be safely executed by one thread at a
time
• A lock: an object that is “held” by one thread
at a time, then “released”
Synchronization in Java (1)
• Any object can serve as a lock
– Separate object: Object myLock = new Object();
– Current instance: the this object
• Enclose lines of code in a synchronized block
synchronized(myLock) {
// code here
}
• More than one thread could try to execute this code,
but one acquires the lock and the others “block” or
wait until the first thread releases the lock
Synchronized Methods
• Common situation: all the code in a method is a
critical section
– I.e. only one thread at a time should execute that
method
– E.g. a getter or setter or mutator, or something that
changes shared state info (e.g. a Map of important
data)
• Java makes it easy: add synchronized keyword to
method signature. E.g.
public synchronized void update(…) {
Summary So Far
• Concurrent access to shared data
– Can lead to serious, hard-to-find problems
– E.g. race conditions
• The concept of a lock
• Synchronized blocks of code or methods
– One thread at a time
– While first thread is executing it, others block
More Advanced Synchronization
• A semaphore object
– Allows simultaneous access by N threads
– If N==1, then this is known as a mutex (mutual exclusion)
– Java has a class Semaphore
• Java class CountDownLatch
– Created with a count (often a number of “worker”
threads). Say object is allWorkersDone
– Another thread (a “manager”) waits for all the workers to
call countDown() on that object
– So manager blocks with: allWorkersDone.await()
Barriers
• Java class CyclicBarrier
– A rendezvous point or barrier point
– Worker threads wait at a spot until all get there
– Then all proceed
Using CountDownLatch
• Here are some common scenarios and demo
programs for them
• You’ll use the last of these for the War card-
game program!
Scenario #1
• A “manager” thread and N “worker” threads
• Manager starts workers but then must wait for them to
finish before doing follow-up work
• Solution:
– Manager creates a CountDownLatch with value N
– After workers starts, manager calls await() on that
– When each worker completes its work, it calls
countDown() on the latch
– After all N call countDown(), manager is un-blocked and
does follow-up work
• Example use: parallel divide and conquer like
mergesort
• Code example: SyncDemo0.java
Scenario #2
• A “manager” thread and N “worker” threads
• Manager starts workers but wants them to “hold”
before doing real work until it says “go”
• Solution:
– Manager creates a CountDownLatch with value 1
– After each workers start, it calls await() on that Latch
– At some point, when ready, the manager calls
countDown() on that Latch
– Now Workers free to continue with their work
• Code example: SyncDemo1.java
Scenario #3
• Work done in “rounds” where:
– All workers wait for manager to say “go”
– Each worker does its job and then waits for next round
– Manager waits for all workers to complete a round, then does some
follow-up work
– When that’s done, manager starts next round by telling workers “go”
• Solution: combine the two previous solutions
– First Latch: hold workers until manager is ready
– Second Latch: manager waits until workers finish a round
– Worker’s run() has loop to repeat
– Manager must manage Latches, recreating them at end of round
• Example use: a card game or anything that has that kind of
structure
• Code example: SyncDemo2.java
Summary of last section
• Multiple threads may need to cooperate
– Common situation: some workers and a manager
– One thread may need to wait for one or more thread
to complete
– One or more threads may need to wait to be
“released”
– Or a combination of these situations
• Threads all access a CountDownLatch
– await() used to wait for enough calls to countDown()
End
• Unused slides follow
dfafaf
work
Thr
A
work
Thr
A
Work to
do
Thr
A
await

More Related Content

Similar to cs4240-multithreading.ppt presentation on multi threading

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programmingraksharao
 
Thread presentation
Thread presentationThread presentation
Thread presentationAAshish Ojha
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics modulemanikanta361
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskHoang Ngo
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
Lec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented ProgrammingLec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented ProgrammingBadar Waseer
 

Similar to cs4240-multithreading.ppt presentation on multi threading (20)

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
java threads
java threadsjava threads
java threads
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Threads
ThreadsThreads
Threads
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Thread presentation
Thread presentationThread presentation
Thread presentation
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
multithreading
multithreadingmultithreading
multithreading
 
Lec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented ProgrammingLec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented Programming
 

More from ShrutiPanda12

androidsimplecalculator-200214111221.pdf
androidsimplecalculator-200214111221.pdfandroidsimplecalculator-200214111221.pdf
androidsimplecalculator-200214111221.pdfShrutiPanda12
 
logisticregression-120102011227-phpapp01.pptx
logisticregression-120102011227-phpapp01.pptxlogisticregression-120102011227-phpapp01.pptx
logisticregression-120102011227-phpapp01.pptxShrutiPanda12
 
Stockprice_prediction.pptx for download project
Stockprice_prediction.pptx for download projectStockprice_prediction.pptx for download project
Stockprice_prediction.pptx for download projectShrutiPanda12
 
Administration_Vs_Management for free download the ppt of Android applications
Administration_Vs_Management for free download the ppt of Android applicationsAdministration_Vs_Management for free download the ppt of Android applications
Administration_Vs_Management for free download the ppt of Android applicationsShrutiPanda12
 
HOTEL-MANAGEMENT-SYSTEM-PPT.ppt
HOTEL-MANAGEMENT-SYSTEM-PPT.pptHOTEL-MANAGEMENT-SYSTEM-PPT.ppt
HOTEL-MANAGEMENT-SYSTEM-PPT.pptShrutiPanda12
 
Database management system.pptx
Database management system.pptxDatabase management system.pptx
Database management system.pptxShrutiPanda12
 
logisticregression.ppt
logisticregression.pptlogisticregression.ppt
logisticregression.pptShrutiPanda12
 

More from ShrutiPanda12 (8)

androidsimplecalculator-200214111221.pdf
androidsimplecalculator-200214111221.pdfandroidsimplecalculator-200214111221.pdf
androidsimplecalculator-200214111221.pdf
 
logisticregression-120102011227-phpapp01.pptx
logisticregression-120102011227-phpapp01.pptxlogisticregression-120102011227-phpapp01.pptx
logisticregression-120102011227-phpapp01.pptx
 
Stockprice_prediction.pptx for download project
Stockprice_prediction.pptx for download projectStockprice_prediction.pptx for download project
Stockprice_prediction.pptx for download project
 
Administration_Vs_Management for free download the ppt of Android applications
Administration_Vs_Management for free download the ppt of Android applicationsAdministration_Vs_Management for free download the ppt of Android applications
Administration_Vs_Management for free download the ppt of Android applications
 
HOTEL-MANAGEMENT-SYSTEM-PPT.ppt
HOTEL-MANAGEMENT-SYSTEM-PPT.pptHOTEL-MANAGEMENT-SYSTEM-PPT.ppt
HOTEL-MANAGEMENT-SYSTEM-PPT.ppt
 
Database management system.pptx
Database management system.pptxDatabase management system.pptx
Database management system.pptx
 
logisticregression.ppt
logisticregression.pptlogisticregression.ppt
logisticregression.ppt
 
seminar100326a.pdf
seminar100326a.pdfseminar100326a.pdf
seminar100326a.pdf
 

Recently uploaded

TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportDenish Jangid
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesPooky Knightsmith
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 

cs4240-multithreading.ppt presentation on multi threading

  • 2. Tasks and Threads • A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries use the Runnable interface – work done by method run() • Thread: a Java class for a thread – work done by method run() • How to associate a task with a thread? • How to start a thread?
  • 3. Creating a Task and Thread • Warning: old way(s), new ways • First, if you have a thread object, you can call start() on that object – Makes it available to be run – When it’s time to run it, Thread’s run() is called • So, create a thread using “old” (not good) way – Write class that extends Thread, e.g. MyThread – Define your own run() – Create a MyThread object and call start() on it • We won’t do this! Not good design
  • 4. Runnables and Thread • Use the “task abstraction” and create a class that implements Runnable interface – Define the run() method to do the work you want • Now, two ways to make your task run in a separate thread – Create a Thread object and pass a Runnable to the constructor – As before, call start() on the Thread object
  • 5. Do we need a Thread “manager”? • If your code is responsible for creating a bunch of tasks, linking them with Threads, and starting them all, then you have things to worry about: – What if you start too many threads? Can you manage the number of running threads? – Can you shutdown all the threads? – If one fails, can you restart it?
  • 6. Executors • An Executor is an object that manages running tasks – Submit a Runnable to be run with Executor’s execute() method – So, instead of creating a Thread for your Runnable and calling start() on that, do this: • Get an Executor object, say called exec • Create a Runnable, say called myTask • Submit for running: exec.execute(myTask)
  • 7. How to Get an Executor • Use static methods in Executors library. • Fixed “thread pool”: at most N threads running at one time Executor exec = Executors.newFixedThreadPool(MAX_THREADS); • Unlimited number of threads Executor exec = Executors.newCachedThreadPool();
  • 8. Summary So Far • Create a class that implements a Runnable to be your “worker” • Create Runnable objects • Create an Executor • Submit each Runnable to the Executor which starts it up in a separate thread
  • 9.
  • 10. Synchronization • Understand the issue with concurrent access to shared data? – Data could be a counter (int) or a data structure (e.g. a Map or List or Set) • A critical section: a block of code that can only be safely executed by one thread at a time • A lock: an object that is “held” by one thread at a time, then “released”
  • 11. Synchronization in Java (1) • Any object can serve as a lock – Separate object: Object myLock = new Object(); – Current instance: the this object • Enclose lines of code in a synchronized block synchronized(myLock) { // code here } • More than one thread could try to execute this code, but one acquires the lock and the others “block” or wait until the first thread releases the lock
  • 12. Synchronized Methods • Common situation: all the code in a method is a critical section – I.e. only one thread at a time should execute that method – E.g. a getter or setter or mutator, or something that changes shared state info (e.g. a Map of important data) • Java makes it easy: add synchronized keyword to method signature. E.g. public synchronized void update(…) {
  • 13. Summary So Far • Concurrent access to shared data – Can lead to serious, hard-to-find problems – E.g. race conditions • The concept of a lock • Synchronized blocks of code or methods – One thread at a time – While first thread is executing it, others block
  • 14.
  • 15. More Advanced Synchronization • A semaphore object – Allows simultaneous access by N threads – If N==1, then this is known as a mutex (mutual exclusion) – Java has a class Semaphore • Java class CountDownLatch – Created with a count (often a number of “worker” threads). Say object is allWorkersDone – Another thread (a “manager”) waits for all the workers to call countDown() on that object – So manager blocks with: allWorkersDone.await()
  • 16. Barriers • Java class CyclicBarrier – A rendezvous point or barrier point – Worker threads wait at a spot until all get there – Then all proceed
  • 17. Using CountDownLatch • Here are some common scenarios and demo programs for them • You’ll use the last of these for the War card- game program!
  • 18. Scenario #1 • A “manager” thread and N “worker” threads • Manager starts workers but then must wait for them to finish before doing follow-up work • Solution: – Manager creates a CountDownLatch with value N – After workers starts, manager calls await() on that – When each worker completes its work, it calls countDown() on the latch – After all N call countDown(), manager is un-blocked and does follow-up work • Example use: parallel divide and conquer like mergesort • Code example: SyncDemo0.java
  • 19. Scenario #2 • A “manager” thread and N “worker” threads • Manager starts workers but wants them to “hold” before doing real work until it says “go” • Solution: – Manager creates a CountDownLatch with value 1 – After each workers start, it calls await() on that Latch – At some point, when ready, the manager calls countDown() on that Latch – Now Workers free to continue with their work • Code example: SyncDemo1.java
  • 20. Scenario #3 • Work done in “rounds” where: – All workers wait for manager to say “go” – Each worker does its job and then waits for next round – Manager waits for all workers to complete a round, then does some follow-up work – When that’s done, manager starts next round by telling workers “go” • Solution: combine the two previous solutions – First Latch: hold workers until manager is ready – Second Latch: manager waits until workers finish a round – Worker’s run() has loop to repeat – Manager must manage Latches, recreating them at end of round • Example use: a card game or anything that has that kind of structure • Code example: SyncDemo2.java
  • 21. Summary of last section • Multiple threads may need to cooperate – Common situation: some workers and a manager – One thread may need to wait for one or more thread to complete – One or more threads may need to wait to be “released” – Or a combination of these situations • Threads all access a CountDownLatch – await() used to wait for enough calls to countDown()