SlideShare a Scribd company logo
Multithreading in Java
• Multithreading in java is a process of executing
multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
• But we use multithreading than multiprocessing
because threads share a common memory area. They
don't allocate separate memory area so saves
memory, and context-switching between the threads
takes less time than process.
• Java Multithreading is mostly used in games,
animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and you can 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
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• 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.
What is Thread in java
• A thread is a lightweight 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.
• As shown in the above 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.
Java Thread Methods
Life cycle of a Thread (Thread States)
• A thread can be in one of the five states.
• According to sun, 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. The
java thread states are as follows:
– New
– Runnable
– Running
– Non-Runnable (Blocked)
– Terminated
Life cycle of a 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.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not
eligible to run.
5) Terminated
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:
• By extending Thread class
• By implementing Runnable interface.
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 of Thread class:
– Thread()
– Thread(String name)
– Thread(Runnable r)
– Thread(Runnable r,String name)
Commonly used methods of Thread class:
• 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 (temporarily
cease execution) 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.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state 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.
Runnable interface:
• The Runnable interface should be implemented by any
class whose instances are intended to be executed by a
thread.
• Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
• start() method of Thread class is used to start a newly
created thread.
• It performs following tasks: A new thread starts(with new
callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run()
method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
• If you are not extending the Thread class,your
class object would not be treated as a thread
object.
• So you need to explicitely create Thread class
object.
• We are passing the object of your class that
implements Runnable so that your class run()
method may execute.
Java I/O
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
• We can perform file handling in java by Java I/O API.
Stream
• A stream is a sequence of data.In Java a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
• In java, 3 streams are created for us automatically. All these streams are attached
with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
• Let's see the code to print output and error message to the console.
• System.out.println("simple message");
• System.err.println("error message");
• Let's see the code to get input from console.
• int i=System.in.read();//returns ASCII code of 1st character
• System.out.println((char)i);//will print the character
OutputStream vs InputStream
• The explanation of OutputStream and InputStream classes are
given below:
OutputStream
• Java application uses an output stream to write data to a
destination, it may be a file, an array, peripheral device or socket.
InputStream
• Java application uses an input stream to read data from a source, it
may be a file, an array, peripheral device or socket.
• Let's understand working of Java OutputStream and InputStream by
the figure given below.
• OutputStream class
• OutputStream class is an abstract class. It is the super class of
all classes representing an output stream of bytes. An output
stream accepts output bytes and sends them to some sink.
OutputStream Hierarchy
• InputStream class
• InputStream class is an abstract class. It is the
super class of all classes representing an input
stream of bytes.
InputStream Hierarchy
Java FileOutputStream Class
• Java FileOutputStream is an output stream used for writing
data to a file.
• If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented as well
as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use
FileWriter than FileOutputStream.
FileOutputStream class declaration
• Let's see the declaration for Java.io.FileOutputStream class:
• public class FileOutputStream extends OutputStream
Java FileOutputStream Example 1: write byte
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A
Java FileInputStream Class
• Java FileInputStream class obtains input bytes from a
file. It is used for reading byte-oriented data (streams
of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading
streams of characters, it is recommended to use
FileReader class.
Java FileInputStream class declaration
• Let's see the declaration for java.io.FileInputStream
class:
• public class FileInputStream extends InputStream
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which
is 87 (in byte form). To see the text, you need to convert it into character.
Output:
W
web programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.ppt

More Related Content

Similar to web programming-Multithreading concept in Java.ppt (20)

unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Threads in Java
Threads in Java
HarshaDokula
 
Java threads
Java threads
Prabhakaran V M
 
econtent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java threading
Java threading
Chinh Ngo Nguyen
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
kassyemariyam21
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Multithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
SivaSankari36
 
Multithreading in java
Multithreading in java
junnubabu
 
Module 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Multithreading in java
Multithreading in java
Lovely Professional University
 
Java unit 12
Java unit 12
Shipra Swati
 
L22 multi-threading-introduction
L22 multi-threading-introduction
teach4uin
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
econtent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
kassyemariyam21
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Multithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
SivaSankari36
 
Multithreading in java
Multithreading in java
junnubabu
 
Module 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
L22 multi-threading-introduction
L22 multi-threading-introduction
teach4uin
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 

More from mcjaya2024 (20)

cyber forensics Email Investigations.ppt
cyber forensics Email Investigations.ppt
mcjaya2024
 
Cell Phone and Mobile Devices Forensics.ppt
Cell Phone and Mobile Devices Forensics.ppt
mcjaya2024
 
Computer Forensics Analysis and Validation.ppt
Computer Forensics Analysis and Validation.ppt
mcjaya2024
 
cyber forensics Footprinting and Scanning.ppt
cyber forensics Footprinting and Scanning.ppt
mcjaya2024
 
cyber forensics-enum,sniffing,malware threat.ppt
cyber forensics-enum,sniffing,malware threat.ppt
mcjaya2024
 
Classless Interdomain Data Routing CIDR.ppt
Classless Interdomain Data Routing CIDR.ppt
mcjaya2024
 
Computer Network in Network software.ppt
Computer Network in Network software.ppt
mcjaya2024
 
web program-Extended MARKUP Language XML.ppt
web program-Extended MARKUP Language XML.ppt
mcjaya2024
 
Web programming-Introduction to JSP.pptx
Web programming-Introduction to JSP.pptx
mcjaya2024
 
web program -Life cycle of a servlet.ppt
web program -Life cycle of a servlet.ppt
mcjaya2024
 
web programmimg- concpt in JAVABEANS.ppt
web programmimg- concpt in JAVABEANS.ppt
mcjaya2024
 
web program-Inheritance,pack&except in Java.ppt
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Processing Crime and Incident Scenes.ppt
Processing Crime and Incident Scenes.ppt
mcjaya2024
 
Working with Windows and DOS Systems (1).ppt
Working with Windows and DOS Systems (1).ppt
mcjaya2024
 
enterprise resource plnning ERP vendors.pdf
enterprise resource plnning ERP vendors.pdf
mcjaya2024
 
ERP and elctronic commerce online12.ppt
ERP and elctronic commerce online12.ppt
mcjaya2024
 
Enterprise resourse planning ERPlife cycle.ppt
Enterprise resourse planning ERPlife cycle.ppt
mcjaya2024
 
Project Management Issues in ERP IS 6006.ppt
Project Management Issues in ERP IS 6006.ppt
mcjaya2024
 
mySAP_Supply_Chain_Management_Solution_Map.pdf
mySAP_Supply_Chain_Management_Solution_Map.pdf
mcjaya2024
 
cyber forensics Email Investigations.ppt
cyber forensics Email Investigations.ppt
mcjaya2024
 
Cell Phone and Mobile Devices Forensics.ppt
Cell Phone and Mobile Devices Forensics.ppt
mcjaya2024
 
Computer Forensics Analysis and Validation.ppt
Computer Forensics Analysis and Validation.ppt
mcjaya2024
 
cyber forensics Footprinting and Scanning.ppt
cyber forensics Footprinting and Scanning.ppt
mcjaya2024
 
cyber forensics-enum,sniffing,malware threat.ppt
cyber forensics-enum,sniffing,malware threat.ppt
mcjaya2024
 
Classless Interdomain Data Routing CIDR.ppt
Classless Interdomain Data Routing CIDR.ppt
mcjaya2024
 
Computer Network in Network software.ppt
Computer Network in Network software.ppt
mcjaya2024
 
web program-Extended MARKUP Language XML.ppt
web program-Extended MARKUP Language XML.ppt
mcjaya2024
 
Web programming-Introduction to JSP.pptx
Web programming-Introduction to JSP.pptx
mcjaya2024
 
web program -Life cycle of a servlet.ppt
web program -Life cycle of a servlet.ppt
mcjaya2024
 
web programmimg- concpt in JAVABEANS.ppt
web programmimg- concpt in JAVABEANS.ppt
mcjaya2024
 
web program-Inheritance,pack&except in Java.ppt
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Processing Crime and Incident Scenes.ppt
Processing Crime and Incident Scenes.ppt
mcjaya2024
 
Working with Windows and DOS Systems (1).ppt
Working with Windows and DOS Systems (1).ppt
mcjaya2024
 
enterprise resource plnning ERP vendors.pdf
enterprise resource plnning ERP vendors.pdf
mcjaya2024
 
ERP and elctronic commerce online12.ppt
ERP and elctronic commerce online12.ppt
mcjaya2024
 
Enterprise resourse planning ERPlife cycle.ppt
Enterprise resourse planning ERPlife cycle.ppt
mcjaya2024
 
Project Management Issues in ERP IS 6006.ppt
Project Management Issues in ERP IS 6006.ppt
mcjaya2024
 
mySAP_Supply_Chain_Management_Solution_Map.pdf
mySAP_Supply_Chain_Management_Solution_Map.pdf
mcjaya2024
 
Ad

Recently uploaded (20)

最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
NALCO Green Anode Plant,Compositions of CPC,Pitch
NALCO Green Anode Plant,Compositions of CPC,Pitch
arpitprachi123
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
TEA2016AAT 160 W TV application design example
TEA2016AAT 160 W TV application design example
ssuser1be9ce
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
NALCO Green Anode Plant,Compositions of CPC,Pitch
NALCO Green Anode Plant,Compositions of CPC,Pitch
arpitprachi123
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
TEA2016AAT 160 W TV application design example
TEA2016AAT 160 W TV application design example
ssuser1be9ce
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
Ad

web programming-Multithreading concept in Java.ppt

  • 2. • Multithreading in java is a process of executing multiple threads simultaneously. • Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. • But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. • Java Multithreading is mostly used in games, animation etc.
  • 3. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can 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
  • 4. Multitasking • Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: • Process-based Multitasking(Multiprocessing) • 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.
  • 5. What is Thread in java • A thread is a lightweight 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.
  • 6. • As shown in the above 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.
  • 7. 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.
  • 9. Life cycle of a Thread (Thread States) • A thread can be in one of the five states. • According to sun, 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. The java thread states are as follows: – New – Runnable – Running – Non-Runnable (Blocked) – Terminated
  • 10. Life cycle of a Thread
  • 11. 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. 3) Running The thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 5) Terminated A thread is in terminated or dead state when its run() method exits.
  • 12. How to create thread • There are two ways to create a thread: • By extending Thread class • By implementing Runnable interface. 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 of Thread class: – Thread() – Thread(String name) – Thread(Runnable r) – Thread(Runnable r,String name)
  • 13. Commonly used methods of Thread class: • 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 (temporarily cease execution) 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. • public int getId(): returns the id of the thread. • public Thread.State getState(): returns the state 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.
  • 14. Runnable interface: • The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. • Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. Starting a thread: • start() method of Thread class is used to start a newly created thread. • It performs following tasks: A new thread starts(with new callstack). • The thread moves from New state to the Runnable state. • When the thread gets a chance to execute, its target run() method will run.
  • 15. 1) Java Thread Example by extending Thread class class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } } Output:thread is running...
  • 16. 2) Java Thread Example by implementing Runnable interface class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); t1.start(); } } Output:thread is running...
  • 17. • If you are not extending the Thread class,your class object would not be treated as a thread object. • So you need to explicitely create Thread class object. • We are passing the object of your class that implements Runnable so that your class run() method may execute.
  • 18. Java I/O • Java I/O (Input and Output) is used to process the input and produce the output. • Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. • We can perform file handling in java by Java I/O API. Stream • A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. • In java, 3 streams are created for us automatically. All these streams are attached with console. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream • Let's see the code to print output and error message to the console. • System.out.println("simple message"); • System.err.println("error message");
  • 19. • Let's see the code to get input from console. • int i=System.in.read();//returns ASCII code of 1st character • System.out.println((char)i);//will print the character OutputStream vs InputStream • The explanation of OutputStream and InputStream classes are given below: OutputStream • Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket. InputStream • Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket. • Let's understand working of Java OutputStream and InputStream by the figure given below.
  • 20. • OutputStream class • OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
  • 22. • InputStream class • InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes.
  • 24. Java FileOutputStream Class • Java FileOutputStream is an output stream used for writing data to a file. • If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. FileOutputStream class declaration • Let's see the declaration for Java.io.FileOutputStream class: • public class FileOutputStream extends OutputStream
  • 25. Java FileOutputStream Example 1: write byte import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); fout.write(65); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } } Output: Success... The content of a text file testout.txt is set with the data A. testout.txt A
  • 26. Java FileInputStream Class • Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class. Java FileInputStream class declaration • Let's see the declaration for java.io.FileInputStream class: • public class FileInputStream extends InputStream
  • 27. import java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=fin.read(); System.out.print((char)i); fin.close(); }catch(Exception e){System.out.println(e);} } } Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content: Welcome to javatpoint. After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character. Output: W