SlideShare a Scribd company logo
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

Threading concepts
Threading conceptsThreading concepts
Threading concepts
Raheemaparveen
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Thread
ThreadThread
Thread
Juhi Kumari
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
myrajendra
 
[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
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
teach4uin
 
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
Hitendra Kumar
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Java threads
Java threadsJava threads
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
jehan1987
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 

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.pptx
nimbalkarvikram966
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
madan r
 
Java Threads
Java ThreadsJava Threads
Java Threads
Hamid Ghorbani
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
Java class 6
Java class 6Java class 6
Java class 6
Edureka!
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
sarthakgithub
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Jayant Dalvi
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
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
arnavytstudio2814
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 

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 Codes
DeeptiJava
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
DeeptiJava
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
DeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
DeeptiJava
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
DeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
DeeptiJava
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
DeeptiJava
 
Java I/O
Java I/OJava I/O
Java I/O
DeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
DeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
DeeptiJava
 

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

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

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