SlideShare a Scribd company logo
1 of 20
Internet Programming With
Java
Threads
Submitted by,
M. Kavitha,
II – M.Sc(CS&IT),
Nadar Saraswathi College of
Arts & Science, Theni.
Thread
* A thread is a lightweight sub process, a smallest
unit of processing.
* It is a separate path of execution.
Class ABC
{
-----------
-----------
-----------
-----------
-----------
-----------
-----------
-----------
}
Beginning
Single-threaded body
of execution
End
Fig 1: Single-threaded Program
* Threads are independent, if there occurs exception
in one thread, it doesn't affect other threads.
* It shares a common memory area.
t2
t3
t1
Process 1
Process 2
Process 3
t1
t2
t1
Fig 2 : OS
Figure, thread is executed inside the process. There is
context-switching between the threads.
There can be multiple processes inside the OS and one
process can have multiple threads.
Java Thread Class :
* Thread class is the main class on which java's
multithreading system is based.
* Thread class provide constructors and methods to
create and perform operations on a thread.
* Thread class extends Object class and implements
Runnable interface.
Multithreading :
* Multithreading in java is a process of executing
multiple threads simultaneously.
* Thread is a sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
* A separate memory area to saves memory, and context-
switching between the threads takes less time than process.
Advantages :
1) It doesn't block the user because threads are
independent and perform multiple operations at same time.
2) You can perform many operations together so it
saves time.
3) Threads are independent so it doesn't affect
other threads if exception occur in a single thread.
Main Thread
Thread A Thread B Thread C
Start Start Start
Main Method
Module
Switching Switching
Fig 3 :
Multithreaded Program
Multitasking
* Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU.
* Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
* Each process have its own address in memory i.e. each
process allocates separate memory area.
* Process is heavyweight.
* Cost of communication between the process is high.
* Switching from one process to another require some
time for saving and loading registers, memory maps, updating
lists etc.
2) Thread-based Multitasking (Multithreading)
* Threads share the same address space.
* Thread is lightweight.
* Cost of communication between the thread is low.
Java Thread Method
Methods
start() getName() destroy()
run() setName() interrupt()
sleep() getId() isinterrupt()
currentThread() yield() notify()
join() suspend() toString()
getPriority() resume() notifyAll()
setPriority() stop() enumerate()
Difference between multithreading and multitasking
Multithreading Multitasking
1. It is a programming concept in which a
program or a process is divided into two
or more subprogram or threads that are
executed at the same time in parallel.
1. It is an operating system concept in
which multiple tasks are performed
simultaneously.
2. It supports execution of multiple parts
of a single program simultaneously.
2. It supports execution of multiple
programs simultaneously.
3. The processor has to switch between
different parts or threads of a program.
3. The processor has to switch between
different programs or processes.
4. It is highly efficient. 4. It is less efficient in comparison to
multithreading.
5. A threads is the smallest unit in
multithreading.
5. A program or process is the smallest
unit in a multitasking environment.
6. It helps in developing efficient
programs.
6. It helps in developing efficient
operating system.
7. It is cost-effective in case of context
switching.
7. It is expensive in case of context
switching.
Life cycle of Thread
* During the life cycle of thread, there are many state of
thread.
They include:
1. Newborn State.
2. Runnable State.
3. Running State.
4. Blocked State (Non-Runnable).
5. Dead State (Terminated).
* There is only 4 states in thread life cycle in java new,
runnable , non-runnable and terminated.
* There is no running state.
* But for better understanding the threads, we are
explaining it in the 5 states.
*The life cycle of the thread in java is controlled by JVM.
Newborn
Dead
Blocked
Running Runnable
Yield
Start Stop
Stop
Stop
New Thread
Action
Thread
Idle Thread
(Non-Runnable
Killed Thread
resume
notify
suspend
sleep
wait
Fig 4: Life Cycle of Thread.
1) New
The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the
running thread.
Newborn
Dead State
Runnable
State
3) Running
The thread is in running state if the thread scheduler
has selected it.
i) Suspend() – resume()
ii) Sleep() – Suspend()
iii) Wait() – Notify()
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated (Dead)
A thread is in terminated or dead state when its run()
method exits.
How to create thread :
There are two ways to create a thread.
1. By extending Thread class
2. By implementing Runnable interface.
Extending Thread Class :
1. Declare the class and extending the Thread class.
2. Implement the run() method that is responsible for
executing the sequence of code that the thread will execute.
3. Create a thread object and call the start() method
to initiate the thread execution.
1. Declare the class 2. Implement the
run()
3. Start New thread
class mythread extends
Thread
{
-------------------
-------------------
-------------------
}
public void run()
{
------------------
------------------
------------------
------------------
}
mythread athread=new
mythread();
athread.start();
Implementing Runnable Interface :
1. Declare the class as implementing the Runnable
interface.
2. Implement the run() method.
3. Create a thread by defining an object that is
instantiated from this “runnable” class as the target of the thread.
4. Call the thread’s start() method to run the thread.
Synchronization :
* Java enable us to overcome the problem using a
technique known as synchronization.
* It is a keyword synchronization.
* The method that will read information from a file and
the method that will update the same file may be declared as
synchronized.
Runnable Interface
class x implements Runnable
(
public void run()
{
for(int i=1;i<10,i++)
{
System.out.println(“t Thread:”+i);
}
}
class runnabletest
{
public static void main(String args[ ])
{
x runnable=new x();
Thread threadx=new Thread(runnable);
threadx.start( );
System.out.println(“End of main thread”);
}
}
Output
End of main thread
Thread : 1
Thread : 2
Thread : 3
Thread : 4
Thread : 5
Thread : 6
Thread : 7
Thread : 8
Thread : 9
Thread : 10
End of thread
Program 1:
Runnable Interface
Priority of a Thread (Thread Priority) :
* Each thread have a priority. Priorities are represented
by a number between 1 and 10.
* Thread scheduler schedules the threads according to
priority (known as preemptive scheduling).
* But it is not guaranteed because it depends on JVM
specification that which scheduling.
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).
* The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
Example of Priority of a Thread
class TestMultiPriority1 extends Thread
{
public void run() {
System.out.println("running thread name is:“
+Thread.currentThread().getName());
System.out.println("running thread priority is:“
+Thread.currentThread().getPriority()); }
public static void main(String args[]) {
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority( Thread. MIN_PRIORITY);
m2.setPriority( Thread. MAX_PRIORITY);
m1.start();
m2.start(); }
}
Thread Priority Output
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Thank You

More Related Content

What's hot

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-javaaalipalh
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in javaAbhra Basak
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 

What's hot (19)

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java threading
Java threadingJava threading
Java threading
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
javathreads
javathreadsjavathreads
javathreads
 
Java threads
Java threadsJava threads
Java threads
 
Thread
ThreadThread
Thread
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 

Similar to Internet Programming with Java

Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
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
 
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.pptxArulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptxTREXSHyNE
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfGouthamSoma1
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.pptsarthakgithub
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.pptssuserec53e73
 

Similar to Internet Programming with Java (20)

Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on 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
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 

More from kavitha muneeshwaran (13)

Physical Security
Physical SecurityPhysical Security
Physical Security
 
Digital Audio
Digital AudioDigital Audio
Digital Audio
 
Java
JavaJava
Java
 
Data structure
Data structureData structure
Data structure
 
Digital image processing
Digital image processing  Digital image processing
Digital image processing
 
Staffing level estimation
Staffing level estimation Staffing level estimation
Staffing level estimation
 
Data Integration and Transformation in Data mining
Data Integration and Transformation in Data miningData Integration and Transformation in Data mining
Data Integration and Transformation in Data mining
 
Transaction Management - Deadlock Handling
Transaction Management - Deadlock HandlingTransaction Management - Deadlock Handling
Transaction Management - Deadlock Handling
 
Process
ProcessProcess
Process
 
Digital Logic circuit
Digital Logic circuitDigital Logic circuit
Digital Logic circuit
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
I/O system in intel 80386 microcomputer architecture
I/O system in intel 80386 microcomputer architectureI/O system in intel 80386 microcomputer architecture
I/O system in intel 80386 microcomputer architecture
 
narrow Band ISDN
narrow Band ISDNnarrow Band ISDN
narrow Band ISDN
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Internet Programming with Java

  • 1. Internet Programming With Java Threads Submitted by, M. Kavitha, II – M.Sc(CS&IT), Nadar Saraswathi College of Arts & Science, Theni.
  • 2. Thread * A thread is a lightweight sub process, a smallest unit of processing. * It is a separate path of execution. Class ABC { ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- } Beginning Single-threaded body of execution End Fig 1: Single-threaded Program
  • 3. * Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. * It shares a common memory area. t2 t3 t1 Process 1 Process 2 Process 3 t1 t2 t1 Fig 2 : OS
  • 4. Figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. Java Thread Class : * Thread class is the main class on which java's multithreading system is based. * Thread class provide constructors and methods to create and perform operations on a thread. * Thread class extends Object class and implements Runnable interface.
  • 5. Multithreading : * Multithreading in java is a process of executing multiple threads simultaneously. * Thread is a sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. * A separate memory area to saves memory, and context- switching between the threads takes less time than process. Advantages : 1) It doesn't block the user because threads are independent and perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
  • 6. Main Thread Thread A Thread B Thread C Start Start Start Main Method Module Switching Switching Fig 3 : Multithreaded Program
  • 7. Multitasking * Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. * Multitasking can be achieved by two ways: 1. Process-based Multitasking(Multiprocessing) 2. Thread-based Multitasking(Multithreading) 1) Process-based Multitasking (Multiprocessing) * Each process have its own address in memory i.e. each process allocates separate memory area. * Process is heavyweight. * Cost of communication between the process is high. * Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
  • 8. 2) Thread-based Multitasking (Multithreading) * Threads share the same address space. * Thread is lightweight. * Cost of communication between the thread is low. Java Thread Method Methods start() getName() destroy() run() setName() interrupt() sleep() getId() isinterrupt() currentThread() yield() notify() join() suspend() toString() getPriority() resume() notifyAll() setPriority() stop() enumerate()
  • 9. Difference between multithreading and multitasking Multithreading Multitasking 1. It is a programming concept in which a program or a process is divided into two or more subprogram or threads that are executed at the same time in parallel. 1. It is an operating system concept in which multiple tasks are performed simultaneously. 2. It supports execution of multiple parts of a single program simultaneously. 2. It supports execution of multiple programs simultaneously. 3. The processor has to switch between different parts or threads of a program. 3. The processor has to switch between different programs or processes. 4. It is highly efficient. 4. It is less efficient in comparison to multithreading. 5. A threads is the smallest unit in multithreading. 5. A program or process is the smallest unit in a multitasking environment. 6. It helps in developing efficient programs. 6. It helps in developing efficient operating system. 7. It is cost-effective in case of context switching. 7. It is expensive in case of context switching.
  • 10. Life cycle of Thread * During the life cycle of thread, there are many state of thread. They include: 1. Newborn State. 2. Runnable State. 3. Running State. 4. Blocked State (Non-Runnable). 5. Dead State (Terminated). * There is only 4 states in thread life cycle in java new, runnable , non-runnable and terminated. * There is no running state. * But for better understanding the threads, we are explaining it in the 5 states. *The life cycle of the thread in java is controlled by JVM.
  • 11. Newborn Dead Blocked Running Runnable Yield Start Stop Stop Stop New Thread Action Thread Idle Thread (Non-Runnable Killed Thread resume notify suspend sleep wait Fig 4: Life Cycle of Thread.
  • 12. 1) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. Newborn Dead State Runnable State
  • 13. 3) Running The thread is in running state if the thread scheduler has selected it. i) Suspend() – resume() ii) Sleep() – Suspend() iii) Wait() – Notify()
  • 14. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 5) Terminated (Dead) A thread is in terminated or dead state when its run() method exits. How to create thread : There are two ways to create a thread. 1. By extending Thread class 2. By implementing Runnable interface.
  • 15. Extending Thread Class : 1. Declare the class and extending the Thread class. 2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start() method to initiate the thread execution. 1. Declare the class 2. Implement the run() 3. Start New thread class mythread extends Thread { ------------------- ------------------- ------------------- } public void run() { ------------------ ------------------ ------------------ ------------------ } mythread athread=new mythread(); athread.start();
  • 16. Implementing Runnable Interface : 1. Declare the class as implementing the Runnable interface. 2. Implement the run() method. 3. Create a thread by defining an object that is instantiated from this “runnable” class as the target of the thread. 4. Call the thread’s start() method to run the thread. Synchronization : * Java enable us to overcome the problem using a technique known as synchronization. * It is a keyword synchronization. * The method that will read information from a file and the method that will update the same file may be declared as synchronized.
  • 17. Runnable Interface class x implements Runnable ( public void run() { for(int i=1;i<10,i++) { System.out.println(“t Thread:”+i); } } class runnabletest { public static void main(String args[ ]) { x runnable=new x(); Thread threadx=new Thread(runnable); threadx.start( ); System.out.println(“End of main thread”); } } Output End of main thread Thread : 1 Thread : 2 Thread : 3 Thread : 4 Thread : 5 Thread : 6 Thread : 7 Thread : 8 Thread : 9 Thread : 10 End of thread Program 1: Runnable Interface
  • 18. Priority of a Thread (Thread Priority) : * Each thread have a priority. Priorities are represented by a number between 1 and 10. * Thread scheduler schedules the threads according to priority (known as preemptive scheduling). * But it is not guaranteed because it depends on JVM specification that which scheduling. 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). * The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
  • 19. Example of Priority of a Thread class TestMultiPriority1 extends Thread { public void run() { System.out.println("running thread name is:“ +Thread.currentThread().getName()); System.out.println("running thread priority is:“ +Thread.currentThread().getPriority()); } public static void main(String args[]) { TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new TestMultiPriority1(); m1.setPriority( Thread. MIN_PRIORITY); m2.setPriority( Thread. MAX_PRIORITY); m1.start(); m2.start(); } } Thread Priority Output running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1