SlideShare a Scribd company logo
1 of 22
Java/J2EE Programming Training
Threads
Page 1Classification: Restricted
Agenda
• Threads
Page 2Classification: Restricted
Objectives
• Write code to define, instantiate and start new threads using both
java.lang.Thread and java.lang.Runnable.
• Recognize conditions that might prevent a thread from executing.
• Write code using synchronized wait, notify and notifyAll to protect
against concurrent access problems and to communicate between
threads.
• Define the interaction among threads and object locks when executing
synchronized wait, notify or notifyAll.
Page 3Classification: Restricted
Creating Threads
• Threads can be created in two ways- 1. By extending the Thread class 2.
By implementing the Runnable Interface
Eg: class NewThread extends Thread {
public void run()
{ System.out.println(“Running”); } }
• To implement Runnable you need to define only one method – public
void run()
Eg: class MadeRunnable implements Runnable {
public void run()
{ System.out.println(“Running”); } }
Page 4Classification: Restricted
Instantiating Threads
• A thread in Java is represented by an object of the Thread class.
• The Thread constructors available are
Thread()
Thread(String name)
Thread(Runnable runnable)
Thread(Runnable runnable, String name)
Thread(ThreadGroup g, Runnable runnable)
Thread(ThreadGroup g, Runnable runnable, String name)
Thread(ThreadGroup g, String name)
Page 5Classification: Restricted
Starting a Thread
• When start() method is called on a Thread object, the thread moves from
the new state to the runnable state
• When the Thread Scheduler gives the thread a chance to execute, the
run() method will be invoked
Eg:
class MyRunnable implements Runnable {
public void run() {
for(int i=0;i<10;i++) System.out.println(“Running”); }
public static void main(String args[])
{
Thread t=new Thread(new MyRunnable());
t.start();
} }
Page 6Classification: Restricted
From Sun tutorial:
Life Cycle of Java Threads
Page 7Classification: Restricted
Life Cycle of Java Threads
Page 8Classification: Restricted
Waiting/
blocking
New
Runnable Running Dead
Transitioning between thread states
Page 9Classification: Restricted
Sleep, Yield, isAlive
• The sleep() method puts the currently executing thread to sleep for a given
time in milliseconds
public static void sleep(long millis) throws InterruptedException
• The yield() method causes the current thread to move from the running state
to the runnable state, so that another thread can have a chance. There is no
guarantee that the next thread chosen for running will be a different thread
public static void yield() – not used now
• The isAlive() method returns true if the thread upon which it is called has
been started, but not yet dead
public final boolean isAlive()
Page 10Classification: Restricted
Setting Thread Priority
• By default every thread gets the priority of the thread of execution that
creates it
• The setPriority() method is used to set the priority of a Thread, which
varies from 1 to 10
Eg:
MyRunnable runnable=new MyRunnable();
Thread t=new Thread();
t.setPriority(8);
t.start();
• The Thread class has 3 constants – Thread.NORM_PRIORITY(5),
Thread.MIN_PRIORITY(1) and Thread.MAX_PRIORITY(10)
Page 11Classification: Restricted
join()
• When a thread calls join() on another thread, the currently running thread
will wait until the thread it joins with has completed
Eg:
Thread t=new Thread();
t.start();
t.join();
• The overloaded join() methods are
void join() - Waits for this thread to die
void join(long millis)
- Waits at most millis milliseconds for this thread to die.
void join(long millis, int nanos)
Page 12Classification: Restricted
Extra points to remember…
• Many threads can be in the runnable state, but only one thread can be
actually running at a time
• The order in which threads were started might differ from the order in
which they actually run
• It is legal to invoke the run() method directly, but it does not start a new
thread of execution
• start() method should be invoked only once on a Thread object, else it
will throw an exception
• A thread is considered dead, when it’s run method returns. A dead
thread cannot be started again
• sleep() and yield() are static methods
Page 13Classification: Restricted
Objectives
• Write code using synchronized wait, notify and notifyAll to protect
against concurrent access problems and to communicate between
threads.
• Define the interaction among threads and object locks when executing
synchronized wait, notify or notifyAll.
Page 14Classification: Restricted
Synchronization
• Every object in Java has one and only one lock which ensures synchronized
access to the resource
• If a thread has obtained the lock, no other thread can enter the
synchronized code till the lock is released
• When the thread holding the lock exits the synchronized code, the lock is
released. Now some other thread can enter the synchronized code.
• If a thread tries to get the lock of an object and finds that the lock is already
taken, the thread goes into a blocked state till the lock is released
Page 15Classification: Restricted
synchronized keyword
• synchronized keyword can be used as a method modifier or to start a
synchronized block of code. It prevents the method or block from being
accessed by multiple threads
• To synchronize a block of code, the argument passed should be the object
whose lock you want to synchronize on
Syntax:
synchronized(obj){
// here add statements to be synchronized
}
// obj is the object being synchronized
Page 16Classification: Restricted
Example – synchronized method
• class ThreadTest implements Runnable{
• public void call(String msg) {
• Synchronized ( new ThreadTest()) {
• System.out.print("("+msg);
• }
• Synchronized ( new ThreadTest()) {
• System.out.print("("+msg);
• }
• try{ Thread.sleep(5000); }
• catch (InterruptedException e){}
• System.out.println(")");
• }
• public void run() {
• call(Thread.currentThread().getName());
• }
• public static void main(String args[]) {
• ThreadTest t=new ThreadTest();
• Thread t1=new Thread(t);
• t1.start();
• Thread t2=new Thread(t);
• t2.start(); } }
Page 17Classification: Restricted
Example – synchronized block
Eg: class ThreadTest implements Runnable{
• public void call(String msg) {
• System.out.print("("+msg);
• try{ Thread.sleep(5000); }
• catch (InterruptedException e){}
• System.out.println(")"); }
• public void run() {
synchronized(this) {call(Thread.currentThread().getName()); }
• }
• public static void main(String args[]) {
• ThreadTest t=new ThreadTest();
• Thread t1=new Thread(t); t1.start();
• Thread t2=new Thread(t); t2.start();
• } }
Page 18Classification: Restricted
wait() and notify()
• The methods wait(), notify() and notifyAll() are defined in the
java.lang.Object class
• A thread gives up the lock on a synchronized object and moves from the
running state to the waiting state when the wait() method is invoked
• The notify() method is used to signal one of the threads waiting on the
object to return to the runnable state
• The notifyAll() method sends the signal to all the threads waiting on the
object to return to the runnable state
• A thread can invoke wait() or notify() on a particular object only if it
currently holds the lock on that object
Page 19Classification: Restricted
Example
• Eg:
public void run() {
synchronized(obj) {
try {
obj.wait();
}
catch(InterruptedException e)
{
}
}
}
Page 20Classification: Restricted
Extra points to remember…
• Static methods can be synchronized, using the lock from the
java.lang.Class object representing that class
• If a thread sleeps while executing synchonized code, the lock is not
released
• Methods or code blocks can be synchronized, but not variables
• A class can have both synchronized and non synchronized methods
• Only one thread can access the synchronized code of an object at a time,
but any number of threads can access the same object’s non-synchronized
code
• wait(), notify() and notifyAll() should be called only from within
synchronized code
Page 21Classification: Restricted
Thank You

More Related Content

What's hot

Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introductionteach4uin
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 

What's hot (20)

Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Thread
ThreadThread
Thread
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Java threads
Java threadsJava threads
Java threads
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 

Similar to Java Thread

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptxHKShab
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.pptsarthakgithub
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
 

Similar to Java Thread (20)

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java class 6
Java class 6Java class 6
Java class 6
 
Java threading
Java threadingJava threading
Java threading
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 

More from DeeptiJava

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesDeeptiJava
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingDeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access SpecifierDeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner ClassDeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate BasicsDeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to JavaDeeptiJava
 

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Java Thread

  • 3. Page 2Classification: Restricted Objectives • Write code to define, instantiate and start new threads using both java.lang.Thread and java.lang.Runnable. • Recognize conditions that might prevent a thread from executing. • Write code using synchronized wait, notify and notifyAll to protect against concurrent access problems and to communicate between threads. • Define the interaction among threads and object locks when executing synchronized wait, notify or notifyAll.
  • 4. Page 3Classification: Restricted Creating Threads • Threads can be created in two ways- 1. By extending the Thread class 2. By implementing the Runnable Interface Eg: class NewThread extends Thread { public void run() { System.out.println(“Running”); } } • To implement Runnable you need to define only one method – public void run() Eg: class MadeRunnable implements Runnable { public void run() { System.out.println(“Running”); } }
  • 5. Page 4Classification: Restricted Instantiating Threads • A thread in Java is represented by an object of the Thread class. • The Thread constructors available are Thread() Thread(String name) Thread(Runnable runnable) Thread(Runnable runnable, String name) Thread(ThreadGroup g, Runnable runnable) Thread(ThreadGroup g, Runnable runnable, String name) Thread(ThreadGroup g, String name)
  • 6. Page 5Classification: Restricted Starting a Thread • When start() method is called on a Thread object, the thread moves from the new state to the runnable state • When the Thread Scheduler gives the thread a chance to execute, the run() method will be invoked Eg: class MyRunnable implements Runnable { public void run() { for(int i=0;i<10;i++) System.out.println(“Running”); } public static void main(String args[]) { Thread t=new Thread(new MyRunnable()); t.start(); } }
  • 7. Page 6Classification: Restricted From Sun tutorial: Life Cycle of Java Threads
  • 9. Page 8Classification: Restricted Waiting/ blocking New Runnable Running Dead Transitioning between thread states
  • 10. Page 9Classification: Restricted Sleep, Yield, isAlive • The sleep() method puts the currently executing thread to sleep for a given time in milliseconds public static void sleep(long millis) throws InterruptedException • The yield() method causes the current thread to move from the running state to the runnable state, so that another thread can have a chance. There is no guarantee that the next thread chosen for running will be a different thread public static void yield() – not used now • The isAlive() method returns true if the thread upon which it is called has been started, but not yet dead public final boolean isAlive()
  • 11. Page 10Classification: Restricted Setting Thread Priority • By default every thread gets the priority of the thread of execution that creates it • The setPriority() method is used to set the priority of a Thread, which varies from 1 to 10 Eg: MyRunnable runnable=new MyRunnable(); Thread t=new Thread(); t.setPriority(8); t.start(); • The Thread class has 3 constants – Thread.NORM_PRIORITY(5), Thread.MIN_PRIORITY(1) and Thread.MAX_PRIORITY(10)
  • 12. Page 11Classification: Restricted join() • When a thread calls join() on another thread, the currently running thread will wait until the thread it joins with has completed Eg: Thread t=new Thread(); t.start(); t.join(); • The overloaded join() methods are void join() - Waits for this thread to die void join(long millis) - Waits at most millis milliseconds for this thread to die. void join(long millis, int nanos)
  • 13. Page 12Classification: Restricted Extra points to remember… • Many threads can be in the runnable state, but only one thread can be actually running at a time • The order in which threads were started might differ from the order in which they actually run • It is legal to invoke the run() method directly, but it does not start a new thread of execution • start() method should be invoked only once on a Thread object, else it will throw an exception • A thread is considered dead, when it’s run method returns. A dead thread cannot be started again • sleep() and yield() are static methods
  • 14. Page 13Classification: Restricted Objectives • Write code using synchronized wait, notify and notifyAll to protect against concurrent access problems and to communicate between threads. • Define the interaction among threads and object locks when executing synchronized wait, notify or notifyAll.
  • 15. Page 14Classification: Restricted Synchronization • Every object in Java has one and only one lock which ensures synchronized access to the resource • If a thread has obtained the lock, no other thread can enter the synchronized code till the lock is released • When the thread holding the lock exits the synchronized code, the lock is released. Now some other thread can enter the synchronized code. • If a thread tries to get the lock of an object and finds that the lock is already taken, the thread goes into a blocked state till the lock is released
  • 16. Page 15Classification: Restricted synchronized keyword • synchronized keyword can be used as a method modifier or to start a synchronized block of code. It prevents the method or block from being accessed by multiple threads • To synchronize a block of code, the argument passed should be the object whose lock you want to synchronize on Syntax: synchronized(obj){ // here add statements to be synchronized } // obj is the object being synchronized
  • 17. Page 16Classification: Restricted Example – synchronized method • class ThreadTest implements Runnable{ • public void call(String msg) { • Synchronized ( new ThreadTest()) { • System.out.print("("+msg); • } • Synchronized ( new ThreadTest()) { • System.out.print("("+msg); • } • try{ Thread.sleep(5000); } • catch (InterruptedException e){} • System.out.println(")"); • } • public void run() { • call(Thread.currentThread().getName()); • } • public static void main(String args[]) { • ThreadTest t=new ThreadTest(); • Thread t1=new Thread(t); • t1.start(); • Thread t2=new Thread(t); • t2.start(); } }
  • 18. Page 17Classification: Restricted Example – synchronized block Eg: class ThreadTest implements Runnable{ • public void call(String msg) { • System.out.print("("+msg); • try{ Thread.sleep(5000); } • catch (InterruptedException e){} • System.out.println(")"); } • public void run() { synchronized(this) {call(Thread.currentThread().getName()); } • } • public static void main(String args[]) { • ThreadTest t=new ThreadTest(); • Thread t1=new Thread(t); t1.start(); • Thread t2=new Thread(t); t2.start(); • } }
  • 19. Page 18Classification: Restricted wait() and notify() • The methods wait(), notify() and notifyAll() are defined in the java.lang.Object class • A thread gives up the lock on a synchronized object and moves from the running state to the waiting state when the wait() method is invoked • The notify() method is used to signal one of the threads waiting on the object to return to the runnable state • The notifyAll() method sends the signal to all the threads waiting on the object to return to the runnable state • A thread can invoke wait() or notify() on a particular object only if it currently holds the lock on that object
  • 20. Page 19Classification: Restricted Example • Eg: public void run() { synchronized(obj) { try { obj.wait(); } catch(InterruptedException e) { } } }
  • 21. Page 20Classification: Restricted Extra points to remember… • Static methods can be synchronized, using the lock from the java.lang.Class object representing that class • If a thread sleeps while executing synchonized code, the lock is not released • Methods or code blocks can be synchronized, but not variables • A class can have both synchronized and non synchronized methods • Only one thread can access the synchronized code of an object at a time, but any number of threads can access the same object’s non-synchronized code • wait(), notify() and notifyAll() should be called only from within synchronized code