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
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.
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