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)

DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 

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