SlideShare a Scribd company logo
© Amir Kirsh
Threads
Written by Amir Kirsh
2
Lesson’s Objectives
By the end of this lesson you will:
• Be familiar with the Java threads syntax and API
• Be able to create Java multithreaded applications
Agenda • Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• Thread Pools
• Exercise
4
Threads Overview
– Threads allow the program to run tasks in parallel
– In many cases threads need to be synchronized,
that is, be kept not to handle the same data in
memory concurrently
– There are cases in which a thread needs to wait
for another thread before proceeding
Never use thread-per-session – this is a wrong and
un-scaled architecture – use instead Thread Pools
Agenda • Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• Thread Pools
• Exercise
6
Threads in Java
The operation we want to be threaded:
public class PrintNumbers {
static public void printNumbers() {
for(int i=0; i<1000; i++) {
System.out.println(
Thread.currentThread().getId() +
": " + i);
}
}
}
7
Threads in Java
Option 1 – extending class Thread:
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("Thread1 ThreadId: " +
Thread.currentThread().getId());
// do our thing
PrintNumbers.printNumbers();
// the super doesn't anything,
// but just for the courtesy and good practice
super.run();
}
}
8
Threads in Java
Option 1 – extending class Thread (cont’):
static public void main(String[] args) {
System.out.println("Main ThreadId: " +
Thread.currentThread().getId());
for(int i=0; i<3; i++) {
new Thread1().start(); // don't call run!
// (if you want a separate thread)
}
printNumbers();
}
9
Threads in Java
Option 2 – implementing Runnable:
public class Thread2 implements Runnable {
@Override
public void run() {
System.out.println("Thread2 ThreadId: " +
Thread.currentThread().getId());
// do our thing
PrintNumbers.printNumbers();
}
}
10
Threads in Java
Option 2 – implementing Runnable (cont’):
static public void main(String[] args) {
System.out.println("Main ThreadId: " +
Thread.currentThread().getId());
for(int i=0; i<3; i++) {
new Thread(new Thread2()).start();
// again, don't call run!
// (if you want a separate thread)
}
printNumbers();
}
11
Threads in Java
Option 3 – implementing Runnable as Anonymous:
static public void main(String[] args) {
System.out.println("Main ThreadId: " +
Thread.currentThread().getId());
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread3 ThreadId: " +
Thread.currentThread().getId());
// do our thing
printNumbers();
}
}).start(); // don't call run! ...
printNumbers();
}
Agenda • Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• Thread Pools
• Exercise
13
Synchronization
Synchronization of threads is needed for in order
to control threads coordination, mainly in order to
prevent simultaneous operations on data
For simple synchronization Java provides the
synchronized keyword
For more sophisticated locking mechanisms,
starting from Java 5, the package
java.concurrent.locks provides additional locking
options, see:
http://java.sun.com/javase/6/docs/api/java/util/concurrent/
locks/package-summary.html
14
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() { c++; }
public synchronized void decrement() { c--; }
public synchronized int value() { return c; }
}
Synchronization
Example 1 – synchronizing methods:
The synchronized keyword on a method means
that if this is already locked anywhere
(on this method or elsewhere) by another thread,
we need to wait till this is unlocked before
entering the method
Reentrant
is
allowed
15
public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}
Synchronization
Example 2 – synchronizing blocks:
When synchronizing a block, key for the locking
should be supplied (usually would be this)
The advantage of not synchronizing the entire
method is efficiency
16
public class TwoCounters {
private long c1 = 0, c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
Synchronization
Example 3 – synchronizing using different locks:
You must be
absolutely sure
that there is no tie
between c1 and c2
17
public class Screen {
private static Screen theScreen;
private Screen(){…} // private c’tor
public static synchronized getScreen() {
if(theScreen == null) {
theScreen = new Screen();
}
return theScreen;
}
}
Synchronization
Example 4 – synchronizing static methods:
This is a
Singleton
example
It is not the most
efficient way to implement
Singleton in Java
18
Synchronization
Example 4 – synchronizing static methods …
Having a static method be synchronized means that
ALL objects of this type are locked on the method
and can get in one thread at a time.
The lock is the Class object representing this class.
The performance penalty might be sometimes too
high – needs careful attention!
19
public class Screen {
private static Screen theScreen = new Screen();
private Screen(){…} // private c’tor
public static getScreen() {
return theScreen;
}
}
Synchronization
Example 4’ – a better singleton:
No
synchronization
Agenda • Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• Thread Pools
• Exercise
21
wait(), notify(), notifyAll()
This is an optional topic
We may skip it…
22
wait(), notify(), notifyAll()
wait() and notify() allows a thread to
wait for an event
A call to notifyAll() allows all threads that are on
wait() with the same lock to be released
A call to notify() allows one arbitrary thread that is
on a wait() with the same lock to be released
Read:
(a) http://java.sun.com/docs/books/tutorial/
essential/concurrency/guardmeth.html
(b) http://java.sun.com/javase/6/docs/api/
java/lang/Object.html#wait()
Instead of
“busy wait” or
sleep loop!
23
public class Drop {
// Message sent from producer to consumer
private String message;
// A flag, True if consumer should wait for
// producer to send message, False if producer
// should wait for consumer to retrieve message
private boolean empty = true;
...
wait(), notify(), notifyAll()
Example
(from http://java.sun.com/docs/books/tutorial/essential/concurrency/example/Drop.java):
Flag must be used, never
count only on the notify
24
public class Drop {
...
public synchronized String take() {
// Wait until message is available
while (empty) {
// we do nothing on InterruptedException
// since the while condition is checked anyhow
try { wait(); } catch (InterruptedException e) {}
}
// Toggle status and notify on the status change
empty = true;
notifyAll();
return message;
}
...
}
wait(), notify(), notifyAll()
Example (cont’) Must be in
synchronized context
25
public class Drop {
...
public synchronized void put(String message) {
// Wait until message has been retrieved
while (!empty) {
// we do nothing on InterruptedException
// since the while condition is checked anyhow
try { wait(); } catch (InterruptedException e) {}
}
// Toggle status, store message and notify consumer
empty = false;
this.message = message;
notifyAll();
}
...
}
wait(), notify(), notifyAll()
Example (cont’) Must be in
synchronized context
Agenda • Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• Thread Pools
• Exercise
27
Thread Pools
Prevernt the thread-per-session pitfall!
Class ThreadPoolExecutor:
http://java.sun.com/javase/6/docs/api/java/util/concurrent/
ThreadPoolExecutor.html
Agenda • Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• Thread Pools
• Exercise
29
Exercise
Implement a multithreaded application performing
X sessions of the PrintNumbers.printNumbers task,
(presented at the beginning of this lesson) –
with a Thread Pool of Y threads
X and Y should be retrieved from the command-line
30
That concludes this chapter
amirk at mta ac il

More Related Content

What's hot

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
Rafael Winterhalter
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
Neera Mital
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Threads
ThreadsThreads
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
Alex Miller
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
Rafael Winterhalter
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"
Ciklum Minsk
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
xuehan zhu
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
Rafael Winterhalter
 

What's hot (20)

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Thread
ThreadThread
Thread
 
Threads
ThreadsThreads
Threads
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 

Similar to 04 threads

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
RanjithaM32
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
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
WebStackAcademy
 
multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
shikhaverma566116
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
It Academy
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
ssuserec53e73
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
kavitamittal18
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
HemantSharma134028
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
PavanKumar823345
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
Mohit Kumar
 
MULTITHREADING CONCEPT
MULTITHREADING CONCEPTMULTITHREADING CONCEPT
MULTITHREADING CONCEPT
RAVI MAURYA
 
oop-unit-iv-ppt.ppt
oop-unit-iv-ppt.pptoop-unit-iv-ppt.ppt
oop-unit-iv-ppt.ppt
SureshM228
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdf
Rasa72
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
Hari Christian
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 

Similar to 04 threads (20)

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
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
 
multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Java adv
Java advJava adv
Java adv
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
MULTITHREADING CONCEPT
MULTITHREADING CONCEPTMULTITHREADING CONCEPT
MULTITHREADING CONCEPT
 
oop-unit-iv-ppt.ppt
oop-unit-iv-ppt.pptoop-unit-iv-ppt.ppt
oop-unit-iv-ppt.ppt
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdf
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 

Recently uploaded

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 

Recently uploaded (20)

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 

04 threads

  • 2. 2 Lesson’s Objectives By the end of this lesson you will: • Be familiar with the Java threads syntax and API • Be able to create Java multithreaded applications
  • 3. Agenda • Threads Overview • Creating threads in Java • Synchronization • wait() and notify() • Thread Pools • Exercise
  • 4. 4 Threads Overview – Threads allow the program to run tasks in parallel – In many cases threads need to be synchronized, that is, be kept not to handle the same data in memory concurrently – There are cases in which a thread needs to wait for another thread before proceeding Never use thread-per-session – this is a wrong and un-scaled architecture – use instead Thread Pools
  • 5. Agenda • Threads Overview • Creating threads in Java • Synchronization • wait() and notify() • Thread Pools • Exercise
  • 6. 6 Threads in Java The operation we want to be threaded: public class PrintNumbers { static public void printNumbers() { for(int i=0; i<1000; i++) { System.out.println( Thread.currentThread().getId() + ": " + i); } } }
  • 7. 7 Threads in Java Option 1 – extending class Thread: public class Thread1 extends Thread { @Override public void run() { System.out.println("Thread1 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers.printNumbers(); // the super doesn't anything, // but just for the courtesy and good practice super.run(); } }
  • 8. 8 Threads in Java Option 1 – extending class Thread (cont’): static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread1().start(); // don't call run! // (if you want a separate thread) } printNumbers(); }
  • 9. 9 Threads in Java Option 2 – implementing Runnable: public class Thread2 implements Runnable { @Override public void run() { System.out.println("Thread2 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers.printNumbers(); } }
  • 10. 10 Threads in Java Option 2 – implementing Runnable (cont’): static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread(new Thread2()).start(); // again, don't call run! // (if you want a separate thread) } printNumbers(); }
  • 11. 11 Threads in Java Option 3 – implementing Runnable as Anonymous: static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); new Thread(new Runnable() { @Override public void run() { System.out.println("Thread3 ThreadId: " + Thread.currentThread().getId()); // do our thing printNumbers(); } }).start(); // don't call run! ... printNumbers(); }
  • 12. Agenda • Threads Overview • Creating threads in Java • Synchronization • wait() and notify() • Thread Pools • Exercise
  • 13. 13 Synchronization Synchronization of threads is needed for in order to control threads coordination, mainly in order to prevent simultaneous operations on data For simple synchronization Java provides the synchronized keyword For more sophisticated locking mechanisms, starting from Java 5, the package java.concurrent.locks provides additional locking options, see: http://java.sun.com/javase/6/docs/api/java/util/concurrent/ locks/package-summary.html
  • 14. 14 public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } } Synchronization Example 1 – synchronizing methods: The synchronized keyword on a method means that if this is already locked anywhere (on this method or elsewhere) by another thread, we need to wait till this is unlocked before entering the method Reentrant is allowed
  • 15. 15 public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } Synchronization Example 2 – synchronizing blocks: When synchronizing a block, key for the locking should be supplied (usually would be this) The advantage of not synchronizing the entire method is efficiency
  • 16. 16 public class TwoCounters { private long c1 = 0, c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } } public void inc2() { synchronized(lock2) { c2++; } } } Synchronization Example 3 – synchronizing using different locks: You must be absolutely sure that there is no tie between c1 and c2
  • 17. 17 public class Screen { private static Screen theScreen; private Screen(){…} // private c’tor public static synchronized getScreen() { if(theScreen == null) { theScreen = new Screen(); } return theScreen; } } Synchronization Example 4 – synchronizing static methods: This is a Singleton example It is not the most efficient way to implement Singleton in Java
  • 18. 18 Synchronization Example 4 – synchronizing static methods … Having a static method be synchronized means that ALL objects of this type are locked on the method and can get in one thread at a time. The lock is the Class object representing this class. The performance penalty might be sometimes too high – needs careful attention!
  • 19. 19 public class Screen { private static Screen theScreen = new Screen(); private Screen(){…} // private c’tor public static getScreen() { return theScreen; } } Synchronization Example 4’ – a better singleton: No synchronization
  • 20. Agenda • Threads Overview • Creating threads in Java • Synchronization • wait() and notify() • Thread Pools • Exercise
  • 21. 21 wait(), notify(), notifyAll() This is an optional topic We may skip it…
  • 22. 22 wait(), notify(), notifyAll() wait() and notify() allows a thread to wait for an event A call to notifyAll() allows all threads that are on wait() with the same lock to be released A call to notify() allows one arbitrary thread that is on a wait() with the same lock to be released Read: (a) http://java.sun.com/docs/books/tutorial/ essential/concurrency/guardmeth.html (b) http://java.sun.com/javase/6/docs/api/ java/lang/Object.html#wait() Instead of “busy wait” or sleep loop!
  • 23. 23 public class Drop { // Message sent from producer to consumer private String message; // A flag, True if consumer should wait for // producer to send message, False if producer // should wait for consumer to retrieve message private boolean empty = true; ... wait(), notify(), notifyAll() Example (from http://java.sun.com/docs/books/tutorial/essential/concurrency/example/Drop.java): Flag must be used, never count only on the notify
  • 24. 24 public class Drop { ... public synchronized String take() { // Wait until message is available while (empty) { // we do nothing on InterruptedException // since the while condition is checked anyhow try { wait(); } catch (InterruptedException e) {} } // Toggle status and notify on the status change empty = true; notifyAll(); return message; } ... } wait(), notify(), notifyAll() Example (cont’) Must be in synchronized context
  • 25. 25 public class Drop { ... public synchronized void put(String message) { // Wait until message has been retrieved while (!empty) { // we do nothing on InterruptedException // since the while condition is checked anyhow try { wait(); } catch (InterruptedException e) {} } // Toggle status, store message and notify consumer empty = false; this.message = message; notifyAll(); } ... } wait(), notify(), notifyAll() Example (cont’) Must be in synchronized context
  • 26. Agenda • Threads Overview • Creating threads in Java • Synchronization • wait() and notify() • Thread Pools • Exercise
  • 27. 27 Thread Pools Prevernt the thread-per-session pitfall! Class ThreadPoolExecutor: http://java.sun.com/javase/6/docs/api/java/util/concurrent/ ThreadPoolExecutor.html
  • 28. Agenda • Threads Overview • Creating threads in Java • Synchronization • wait() and notify() • Thread Pools • Exercise
  • 29. 29 Exercise Implement a multithreaded application performing X sessions of the PrintNumbers.printNumbers task, (presented at the beginning of this lesson) – with a Thread Pool of Y threads X and Y should be retrieved from the command-line
  • 30. 30 That concludes this chapter amirk at mta ac il