SlideShare a Scribd company logo
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
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
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
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Java threads
Java threadsJava threads
Thread
ThreadThread
Thread
Juhi Kumari
 
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 Java
M. 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 multithreading
Kuntal 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 language
arnavytstudio2814
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
ssuserec53e73
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
madan r
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
Archana Gopinath
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
sarthakgithub
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
PragatiSutar4
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
ssuserec53e73
 

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

Physical Security
Physical SecurityPhysical Security
Physical Security
kavitha muneeshwaran
 
Digital Audio
Digital AudioDigital Audio
Digital Audio
kavitha muneeshwaran
 
Data structure
Data structureData structure
Data structure
kavitha muneeshwaran
 
Digital image processing
Digital image processing  Digital image processing
Digital image processing
kavitha muneeshwaran
 
Staffing level estimation
Staffing level estimation Staffing level estimation
Staffing level estimation
kavitha muneeshwaran
 
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
kavitha muneeshwaran
 
Transaction Management - Deadlock Handling
Transaction Management - Deadlock HandlingTransaction Management - Deadlock Handling
Transaction Management - Deadlock Handling
kavitha muneeshwaran
 
Process
ProcessProcess
Digital Logic circuit
Digital Logic circuitDigital Logic circuit
Digital Logic circuit
kavitha muneeshwaran
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
kavitha muneeshwaran
 
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
kavitha muneeshwaran
 
narrow Band ISDN
narrow Band ISDNnarrow Band ISDN
narrow Band ISDN
kavitha muneeshwaran
 

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

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .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