SlideShare une entreprise Scribd logo
1  sur  24
MultithreadingMultithreading
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Java and Data StructuresJava and Data Structures
Introduction
• Multithreading in java is a process of executing
multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing.
• Java Multithreading is mostly used in games,
animation etc.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread
• A thread is a light-weight sub process, a smallest unit of
processing. It is a separate path of execution.
• Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads.
• It shares a common memory area.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
t1
t2
t3
Process1
Process2
Process3
Life Cycle of Thread
• A thread can be in one of the five states.
• Life cycle of the thread in java is controlled by JVM.
• The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Life Cycle of Thread
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
NewNew
RunnableRunnable
RunningRunning
TerminatedTerminated
Non-
Runnable
(Blocked)
Non-
Runnable
(Blocked)
start()
run()
Method exits
stop()
run()
Sleep done,
resume, notify
Sleep,
suspend, wait
Life Cycle of Thread
1. New state:
– The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
– It is also referred to as newborn state.
1. Runnable state:
– The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be
the running thread.
– Thread scheduler: Part of JVM that decides which thread
should run.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Life Cycle of Thread
3. Running state:
– thread is in running state if the thread scheduler has
selected it.
– It has been suspended using suspend() method and
retrieved using resume() method.
– It has been made to sleep using sleep() method for specified
time.
– It has been told to wait until some event occurs, using wait()
method, rescheduled using notify() method.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Life Cycle of Thread
4. Non-Runnable(Blocked) state:
– This is the state when the thread is still alive, but is currently
not eligible to run.
5. Terminated (Dead)state:
– A thread is in terminated or dead state when its run()
method exits.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Creating thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread Class
• Thread class provide constructors and methods to create and
perform operations on a thread.
• Thread class extends Object class and implements Runnable
interface.
• Commonly used constructors:
– Thread()
– Thread(String name)
– Thread(Runnable r)
– Thread(Runnable r, String name)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread Class
Commonly used Method:
•public void run(): is used to perform action for a thread.
•public void start(): starts the execution of the thread. JVM calls the run() method
on the thread.
•public void sleep (long miliseconds): Causes the currently executing thread to sleep
for the specified number of milliseconds.
•public void join(): waits for a thread to die.
•public void join (long miliseconds): waits for a thread to die for the specified
miliseconds.
•public int getPriority(): returns the priority of the thread.
•public int setPriority(int priority): changes the priority of the thread.
•public String getName(): returns the name of the thread.
•public void setName (String name): changes the name of the thread.
•public Thread currentThread(): returns the reference of currently executing thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread Class
Commonly used Method:
•public int getId(): returns the id of the thread.
•public boolean isAlive(): tests if the thread is alive.
•public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
•public void suspend(): is used to suspend the thread(depricated).
•public void resume(): is used to resume the suspended thread(depricated).
•public void stop(): is used to stop the thread(depricated).
•public boolean isDaemon(): tests if the thread is a daemon thread.
•public void setDaemon(boolean b): marks the thread as daemon or user thread.
•public void interrupt(): interrupts the thread.
•public boolean isInterrupted(): tests if the thread has been interrupted.
•public static boolean interrupted(): tests if the current thread has been interrupted.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Extending Thread Class
• It includes following steps:
– Declare the class as extending Thread class.
– Implement the run() method that is responsible for
executing the sequence of code that the thread will execute.
– Create a thread object and call the start() method to initiate
the thread execution.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Extending Thread Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class MyThread extends Thread
{
public void run ()
{
System.out.println("Thread Started...!");
for (int count = 1, row = 1; row < 10; row++, count++)
{
for (int i = 0; i < count; i++)
System.out.print ('*');
System.out.print ('n');
}
}
}
class ThreadDemo
{
public static void main (String [] args)
{
MyThread mt = new MyThread ();
mt.start ();
}
}
Implementing Runnable interface
• It includes following steps:
– Declare the class as implementing the runnable interface.
– Implement the run() method.
– Create a thread by defining an object that is instantiated
from this runnable class as the target of the thread.
– Call the threads start() method to run the thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Implementing Runnable interface
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class MyThread implements Runnable
{
public void run ()
{
System.out.println("Thread Started...!");
for (int count = 1, row = 1; row < 10; row++, count++)
{
for (int i = 0; i < count; i++)
System.out.print ('*');
System.out.print ('n');
}
}
}
class ThreadDemo
{
public static void main (String [] args)
{
MyThread mt = new MyThread ();
Thread t = new Thread (mt);
t.start ();
}
}
Sleep()
• sleep() method of Thread class is used to sleep a thread for the
specified milliseconds of time.
• Syntax:
public static void sleep(long miliseconds) throws InterruptedException
public static void sleep(long miliseconds, int nanos) throws InterruptedException
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
join()
• join() method waits for a thread to die.
• In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.
• Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Naming a thread:
• The Thread class provides methods to change and get the name
of a thread.
• public String getName():
– It is used to return the name of a thread.
• public void setName(String name):
– It is used to change the name of a thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
currentThread()
• currentThread() method returns a reference to the currently
executing thread object.
• Syntax:
public static Thread currentThread():
– returns the reference of currently running thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Priority of a Thread (Thread Priority):
• Each thread have a priority.
• Priorities are represented by a number between 1 and 10.
• In most cases, thread scheduler schedules the threads
according to their priority (known as preemptive scheduling).
• But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
• 3 constants defined in Thread class:
– public static int MIN_PRIORITY
– public static int NORM_PRIORITY
– public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY).
• MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Performing multiple task by multiple thread
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Synchronization
• Synchronization in java is the capability of control the access of
multiple threads to any shared resource.
• Java Synchronization is better option where we want to allow
only one thread to access the shared resource.
• synchronized method:
– If you declare any method as synchronized, it is known as synchronized
method.
– Synchronized method is used to lock an object for any shared resource.
– When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its
task.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Q & A

Contenu connexe

Tendances

14 file handling
14 file handling14 file handling
14 file handling
APU
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
myrajendra
 

Tendances (20)

Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
14 file handling
14 file handling14 file handling
14 file handling
 
Applets
AppletsApplets
Applets
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVA
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Java threads
Java threadsJava threads
Java threads
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
OOP java
OOP javaOOP java
OOP java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java Beans
Java BeansJava Beans
Java Beans
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 

En vedette (14)

14. Linked List
14. Linked List14. Linked List
14. Linked List
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
13. Queue
13. Queue13. Queue
13. Queue
 
12. Stack
12. Stack12. Stack
12. Stack
 
8. String
8. String8. String
8. String
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Strings
StringsStrings
Strings
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 

Similaire à 7. 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
arnavytstudio2814
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 

Similaire à 7. Multithreading (20)

L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
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
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Multi threading
Multi threadingMulti threading
Multi threading
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java threading
Java threadingJava threading
Java threading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Multi threading
Multi threadingMulti threading
Multi threading
 

Plus de Nilesh Dalvi (11)

2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 

Dernier

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Dernier (20)

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

7. Multithreading

  • 1. MultithreadingMultithreading By Nilesh Dalvi Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Java and Data StructuresJava and Data Structures
  • 2. Introduction • Multithreading in java is a process of executing multiple threads simultaneously. • Thread is basically a lightweight sub-process, a smallest unit of processing. • Java Multithreading is mostly used in games, animation etc. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3. Thread • A thread is a light-weight sub process, a smallest unit of processing. It is a separate path of execution. • Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. • It shares a common memory area. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). t1 t2 t3 Process1 Process2 Process3
  • 4. Life Cycle of Thread • A thread can be in one of the five states. • Life cycle of the thread in java is controlled by JVM. • The java thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 5. Life Cycle of Thread Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). NewNew RunnableRunnable RunningRunning TerminatedTerminated Non- Runnable (Blocked) Non- Runnable (Blocked) start() run() Method exits stop() run() Sleep done, resume, notify Sleep, suspend, wait
  • 6. Life Cycle of Thread 1. New state: – The thread is in new state if you create an instance of Thread class but before the invocation of start() method. – It is also referred to as newborn state. 1. Runnable state: – The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. – Thread scheduler: Part of JVM that decides which thread should run. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 7. Life Cycle of Thread 3. Running state: – thread is in running state if the thread scheduler has selected it. – It has been suspended using suspend() method and retrieved using resume() method. – It has been made to sleep using sleep() method for specified time. – It has been told to wait until some event occurs, using wait() method, rescheduled using notify() method. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 8. Life Cycle of Thread 4. Non-Runnable(Blocked) state: – This is the state when the thread is still alive, but is currently not eligible to run. 5. Terminated (Dead)state: – A thread is in terminated or dead state when its run() method exits. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 9. Creating thread There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 10. Thread Class • Thread class provide constructors and methods to create and perform operations on a thread. • Thread class extends Object class and implements Runnable interface. • Commonly used constructors: – Thread() – Thread(String name) – Thread(Runnable r) – Thread(Runnable r, String name) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 11. Thread Class Commonly used Method: •public void run(): is used to perform action for a thread. •public void start(): starts the execution of the thread. JVM calls the run() method on the thread. •public void sleep (long miliseconds): Causes the currently executing thread to sleep for the specified number of milliseconds. •public void join(): waits for a thread to die. •public void join (long miliseconds): waits for a thread to die for the specified miliseconds. •public int getPriority(): returns the priority of the thread. •public int setPriority(int priority): changes the priority of the thread. •public String getName(): returns the name of the thread. •public void setName (String name): changes the name of the thread. •public Thread currentThread(): returns the reference of currently executing thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 12. Thread Class Commonly used Method: •public int getId(): returns the id of the thread. •public boolean isAlive(): tests if the thread is alive. •public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. •public void suspend(): is used to suspend the thread(depricated). •public void resume(): is used to resume the suspended thread(depricated). •public void stop(): is used to stop the thread(depricated). •public boolean isDaemon(): tests if the thread is a daemon thread. •public void setDaemon(boolean b): marks the thread as daemon or user thread. •public void interrupt(): interrupts the thread. •public boolean isInterrupted(): tests if the thread has been interrupted. •public static boolean interrupted(): tests if the current thread has been interrupted. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 13. Extending Thread Class • It includes following steps: – Declare the class as extending Thread class. – Implement the run() method that is responsible for executing the sequence of code that the thread will execute. – Create a thread object and call the start() method to initiate the thread execution. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 14. Extending Thread Class Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class MyThread extends Thread { public void run () { System.out.println("Thread Started...!"); for (int count = 1, row = 1; row < 10; row++, count++) { for (int i = 0; i < count; i++) System.out.print ('*'); System.out.print ('n'); } } } class ThreadDemo { public static void main (String [] args) { MyThread mt = new MyThread (); mt.start (); } }
  • 15. Implementing Runnable interface • It includes following steps: – Declare the class as implementing the runnable interface. – Implement the run() method. – Create a thread by defining an object that is instantiated from this runnable class as the target of the thread. – Call the threads start() method to run the thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 16. Implementing Runnable interface Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class MyThread implements Runnable { public void run () { System.out.println("Thread Started...!"); for (int count = 1, row = 1; row < 10; row++, count++) { for (int i = 0; i < count; i++) System.out.print ('*'); System.out.print ('n'); } } } class ThreadDemo { public static void main (String [] args) { MyThread mt = new MyThread (); Thread t = new Thread (mt); t.start (); } }
  • 17. Sleep() • sleep() method of Thread class is used to sleep a thread for the specified milliseconds of time. • Syntax: public static void sleep(long miliseconds) throws InterruptedException public static void sleep(long miliseconds, int nanos) throws InterruptedException Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 18. join() • join() method waits for a thread to die. • In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. • Syntax: public void join()throws InterruptedException public void join(long milliseconds)throws InterruptedException Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 19. Naming a thread: • The Thread class provides methods to change and get the name of a thread. • public String getName(): – It is used to return the name of a thread. • public void setName(String name): – It is used to change the name of a thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 20. currentThread() • currentThread() method returns a reference to the currently executing thread object. • Syntax: public static Thread currentThread(): – returns the reference of currently running thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 21. Priority of a Thread (Thread Priority): • Each thread have a priority. • Priorities are represented by a number between 1 and 10. • In most cases, thread scheduler schedules the threads according to their priority (known as preemptive scheduling). • But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. • 3 constants defined in Thread class: – public static int MIN_PRIORITY – public static int NORM_PRIORITY – public static int MAX_PRIORITY • Default priority of a thread is 5 (NORM_PRIORITY). • MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 22. Performing multiple task by multiple thread Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 23. Synchronization • Synchronization in java is the capability of control the access of multiple threads to any shared resource. • Java Synchronization is better option where we want to allow only one thread to access the shared resource. • synchronized method: – If you declare any method as synchronized, it is known as synchronized method. – Synchronized method is used to lock an object for any shared resource. – When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 24. Q & A