SlideShare a Scribd company logo
www.webstackacademy.com
Java Programming Language SE – 6
Module 15: Threads
Objectives
● Define a thread
● Create separate threads in a Java technology program, controlling
the code and data that are used by that thread
● Control the execution of a thread and write platform- independent
code with threads
● Describe the difficulties that might arise when multiple threads share
data
● Use wait and notify to communicate between threads
● Use synchronized to protect data from corruption
Relevance
● How do you get programs to perform multiple tasks concurrently?
www.webstackacademy.com
Threads
● What are threads?
– Threads are a virtual CPU.
● The three parts of at thread are:
– CPU
– Code
– Data
www.webstackacademy.com
Creating the Thread
public class ThreadTester {
public static void main(String args[]) {
HelloRunner r = new HelloRunner();
Thread t = new Thread(r);
t.start();
}}
class HelloRunner implements Runnable {
int i;
public void run() {
i = 0;
while (true) {
System.out.println("Hello " + i++);
if ( i == 50 ) {
break;
}}}}
www.webstackacademy.com
Creating the Thread
● Multithreaded programming has these characteristics:
● Multiple threads are from one Runnable instance.
● Threads share the same data and code.
● For example:
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
www.webstackacademy.com
Creating the Thread
www.webstackacademy.com
Starting the Thread
● Use the start method.
● Place the thread in a runnable state.
www.webstackacademy.com
Thread Scheduling
www.webstackacademy.com
Thread Scheduling Example
public class Runner implements Runnable {
public void run() {
while (true) {
// do lots of interesting stuff
// ...
// Give other threads a chance
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// This thread’s sleep was interrupted
// by another thread
}}}}
www.webstackacademy.com
Terminating a Thread
public class Runner implements Runnable {
private boolean timeToQuit=false;
public void run() {
while ( ! timeToQuit ) {
// continue doing work
}
// clean up before run() ends
}
public void stopRunning() {
timeToQuit=true;
}}
www.webstackacademy.com
Terminating a Thread
public class ThreadController {
private Runner r = new Runner();
private Thread t = new Thread(r);
public void startThread() {
t.start();
}
public void stopThread() {
// use specific instance of Runner
r.stopRunning();
}}
www.webstackacademy.com
Basic Control of Threads
● Test threads:
– isAlive()
● Access thread priority:
– getPriority()
– setPriority()
● Put threads on hold:
– Thread.sleep()// static method
– join()
– Thread.yield()// static method
www.webstackacademy.com
The join Method
public static void main(String[] args) {
Thread t = new Thread(new Runner());
t.start();
...
// Do stuff in parallel with the other thread for a while
...
// Wait here for the other thread to finish
try {
t.join();
} catch (InterruptedException e) {
// the other thread came back early
}
...
// Now continue in this thread
...}
www.webstackacademy.com
Other Ways to Create
Threads
public class MyThread extends Thread {
public void run() {
while ( true ) {
// do lots of interesting stuff
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// sleep interrupted
}}}
public static void main(String args[]) {
Thread t = new MyThread();
t.start();
}}
www.webstackacademy.com
Selecting a Way to Create
Threads
● Implement Runnable:
– Better object-oriented design
– Single inheritance
– Consistency
● Extend Thread:
– Simpler code
www.webstackacademy.com
Using the synchronized
Keyword
public class MyStack {
int idx = 0;
char [] data = new char[6];
public void push(char c) {
data[idx] = c;
idx++;
}
public char pop() {
idx--;
return data[idx];
}
www.webstackacademy.com
The Object Lock Flag
● Every object has a flag that is a type of lock flag.
● The synchronized enables interaction with the lock flag.
www.webstackacademy.com
The Object Lock Flag
www.webstackacademy.com
The Object Lock Flag
www.webstackacademy.com
Releasing the Lock Flag
The lock flag is released in the following events:
● Released when the thread passes the end of the synchronized code
block
● Released automatically when a break, return, or exception is thrown
by the synchronized code block
www.webstackacademy.com
Using synchronized –
Putting It Together
● All access to delicate data should be synchronized.
● Delicate data protected by synchronized should be private.
www.webstackacademy.com
Using synchronized –
Putting It Together
The following two code segments are equivalent:
public void push(char c) {
synchronized(this) {
// The push method code
}
}
public synchronized void push(char c) {
// The push method code
}
www.webstackacademy.com
Thread State Diagram
With Synchronization
www.webstackacademy.com
Deadlock
A deadlock has the following characteristics:
● It is two threads, each waiting for a lock from the other.
● It is not detected or avoided.
● Deadlock can be avoided by:
– Deciding on the order to obtain locks
– Adhering to this order throughout
– Releasing locks in reverse order
www.webstackacademy.com
Thread Interaction –
wait and notify
● Scenario:
– Consider yourself and a cab driver as two threads.
● The problem:
How do you determine when you are at your destination?
● The solution:
– You notify the cab driver of your destination and relax.
– The driver drives and notifies you upon arrival at your destination.
www.webstackacademy.com
Thread Interaction
Thread interactions include:
● The wait and notify methods
● The pools:
– Wait pool
– Lock pool
www.webstackacademy.com
Thread State Diagram With
wait and notify
www.webstackacademy.com
Monitor Model for
Synchronization
● Leave shared data in a consistent state.
● Ensure programs cannot deadlock.
● Do not put threads expecting different notifications in the same wait
pool.
www.webstackacademy.com
The Producer Class
package mod13;
public class Producer implements Runnable {
private SyncStack theStack;
private int num;
private static int counter = 1;
public Producer (SyncStack s) {
theStack = s;
num = counter++;
}
www.webstackacademy.com
The Producer Class
public void run() {
char c;
for (int i = 0; i < 200; i++) {
c = (char)(Math.random() * 26 +’A’);
theStack.push(c);
System.out.println(“Producer” + num + “: “ + c);
try {
Thread.sleep((int)(Math.random() * 300));
} catch (InterruptedException e) {
// ignore it
}}}}
www.webstackacademy.com
The Consumer Class
package mod13;
public class Consumer implements Runnable {
private SyncStack theStack;
private int num;
private static int counter = 1;
public Consumer (SyncStack s) {
theStack = s;
num = counter++;
}
www.webstackacademy.com
The Consumer Class
public void run() {
char c;
for (int i = 0; i < 200; i++) {
c = theStack.pop();
System.out.println(“Consumer” + num + “: “ + c);
try {
Thread.sleep((int)(Math.random() * 300));
} catch (InterruptedException e) {
// ignore it
}
}
} // END run method
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com
www.webstackacademy.com

More Related Content

What's hot (20)

PDF
Java Concurrency Gotchas
Alex Miller
 
PDF
(not= DSL macros)
Christophe Grand
 
PDF
Csw2016 gawlik bypassing_differentdefenseschemes
CanSecWest
 
PPTX
Threads
Then Murugeshwari
 
PDF
Thread dumps
Ajit Bhingarkar
 
PDF
Understanding Monitor in Dalvik
Haifeng Li
 
PPT
شرح مقرر البرمجة 2 لغة جافا - الوحدة الاولى
جامعة القدس المفتوحة
 
PPTX
Revealing ALLSTOCKER
Masashi Umezawa
 
PDF
De Java 8 a Java 17
Víctor Leonel Orozco López
 
PPT
NS2 Object Construction
Teerawat Issariyakul
 
PPTX
Java concurrency in practice
Mikalai Alimenkou
 
PDF
Thread Dump Analysis
Dmitry Buzdin
 
PPT
20100712-OTcl Command -- Getting Started
Teerawat Issariyakul
 
DOCX
Java 5 concurrency
priyank09
 
PDF
Introduction to node.js
Steven Beeckman
 
PPTX
Concurrency in Java
Allan Huang
 
PPT
NS2 Shadow Object Construction
Teerawat Issariyakul
 
PPTX
Troubleshooting real production problems
Tier1 app
 
KEY
packet destruction in NS2
Teerawat Issariyakul
 
PPTX
Basics of Java Concurrency
kshanth2101
 
Java Concurrency Gotchas
Alex Miller
 
(not= DSL macros)
Christophe Grand
 
Csw2016 gawlik bypassing_differentdefenseschemes
CanSecWest
 
Thread dumps
Ajit Bhingarkar
 
Understanding Monitor in Dalvik
Haifeng Li
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الاولى
جامعة القدس المفتوحة
 
Revealing ALLSTOCKER
Masashi Umezawa
 
De Java 8 a Java 17
Víctor Leonel Orozco López
 
NS2 Object Construction
Teerawat Issariyakul
 
Java concurrency in practice
Mikalai Alimenkou
 
Thread Dump Analysis
Dmitry Buzdin
 
20100712-OTcl Command -- Getting Started
Teerawat Issariyakul
 
Java 5 concurrency
priyank09
 
Introduction to node.js
Steven Beeckman
 
Concurrency in Java
Allan Huang
 
NS2 Shadow Object Construction
Teerawat Issariyakul
 
Troubleshooting real production problems
Tier1 app
 
packet destruction in NS2
Teerawat Issariyakul
 
Basics of Java Concurrency
kshanth2101
 

Similar to Core Java Programming Language (JSE) : Chapter XII - Threads (20)

PPTX
Multi Threading
Ferdin Joe John Joseph PhD
 
PPTX
MULTITHREADING PROGRAMMING AND I/O THREAD
mohanrajm63
 
PPTX
econtent thread in java.pptx
ramyan49
 
PPT
cs4240-multithreading.ppt presentation on multi threading
ShrutiPanda12
 
PDF
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
PPTX
Multithreaded programming
Sonam Sharma
 
PPT
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
PPT
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
PPTX
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
PPTX
Java class 6
Edureka!
 
PPTX
Chap3 multi threaded programming
raksharao
 
PPTX
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
PPT
multithreading, creating a thread and life cycle in java.ppt
shikhaverma566116
 
PPT
Java And Multithreading
Shraddha
 
PPTX
Java programming PPT. .pptx
creativegamerz00
 
PPTX
04 threads-pbl-2-slots
mha4
 
PPTX
04 threads-pbl-2-slots
mha4
 
PPT
Java multi threading
Raja Sekhar
 
PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
MULTITHREADING PROGRAMMING AND I/O THREAD
mohanrajm63
 
econtent thread in java.pptx
ramyan49
 
cs4240-multithreading.ppt presentation on multi threading
ShrutiPanda12
 
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreaded programming
Sonam Sharma
 
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Java class 6
Edureka!
 
Chap3 multi threaded programming
raksharao
 
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
multithreading, creating a thread and life cycle in java.ppt
shikhaverma566116
 
Java And Multithreading
Shraddha
 
Java programming PPT. .pptx
creativegamerz00
 
04 threads-pbl-2-slots
mha4
 
04 threads-pbl-2-slots
mha4
 
Java multi threading
Raja Sekhar
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Ad

More from WebStackAcademy (20)

PDF
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
PDF
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
PDF
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
PDF
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
PDF
Webstack Academy - Internship Kick Off
WebStackAcademy
 
PDF
Building Your Online Portfolio
WebStackAcademy
 
PDF
Front-End Developer's Career Roadmap
WebStackAcademy
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
PDF
Angular - Chapter 5 - Directives
WebStackAcademy
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PDF
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
PDF
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Ad

Recently uploaded (20)

PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
Kubernetes - Architecture & Components.pdf
geethak285
 

Core Java Programming Language (JSE) : Chapter XII - Threads