UNIT-111
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process
allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
What is Thread in Java?
A thread is a lightweight subprocess, the 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 uses a shared memory area .
As shown in the above figure, a 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.
Thre
ad Life Cycle in Java (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
1. New State (Born)
2. Runnable State (Ready)
3. Running State (Execution)
4. Waiting / Blocked
5. Dead / Terminated (Exit)
New: A thread that has been created but not yet started.
Runnable: A thread that is ready to run and waiting for CPU time.
Blocked: A thread that is blocked waiting for a monitor lock.
Waiting: A thread that is waiting indefinitely for another thread to perform a
particular action
Terminated: A thread that has completed its task.
Thread Scheduler in Java
Thread scheduler is the part of processor which execute multiple thread ona
single processor randomly. A component of Java that decides which thread to run
or execute and which thread to wait is called a thread scheduler in Java. In Java,
a thread is only chosen by a thread scheduler if it is in the runnable state. There
are two factors for scheduling a thread i.e. Priority and Time of arrival .And
follows three algorithm
[Link]
[Link]
[Link] ROBIN
Java Threads | How to create a thread in Java
In Java, threads are represented by instances of the Thread class or by
implementing the Runnable interface. The Thread class provides built-in support
for multithreading, while the Runnable interface defines a single method, run()
that contains the code to be executed by the thread. By implementing the
Runnable interface, we can decouple the task from the thread itself, promoting
better code organization and reusability.
There are the following two ways to create a thread:
o By Extending Thread Class
o By Implementing Runnable Interface
Thread Class
The simplest way to create a thread in Java is by extending the Thread class and
overriding its run() method. Thread class provide constructors and methods to
create and perform operations on a thread. Thread class extends Object class and
implements Runnable interface.
Constructors of Thread Class
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r, String name)
By Implementing Runnable Interface
Another approach to creating threads in Java is by implementing the 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 m’ethod named run(). This approach is preferred when we want to separate
the task from the thread itself, promoting better encapsulation and flexibility.
public void run(): is used to perform action for a thread.
Thread Creation
1) Creating Thread by Extending Thread Class
File Name: [Link]
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
Starting a Thread
The start() method of the Thread class is used to start a newly created thread. It
performs the following tasks:
A new thread starts (with new call stack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
2) Java Thread Example by implementing Runnable
interface
FileName: [Link]
class Multi3 implements Runnable{
public void run(){
[Link] ("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
[Link]();
Output:
thread is running...
Creating multiple threads
class multiplethread extends Thread{
public void run(){
String n=[Link]().getName();
for(int i=1;i<=3;i++){
[Link](n);
class multi1
public static void main(String[] args){
multiplethread t1=new multiplethread();
multiplethread t2=new multiplethread();
multiplethread t3=new multiplethread();
[Link]("thread 1");
[Link]("thread 2");
[Link]("thread 3");
[Link]();
[Link]();
[Link]();
THREAD METHODS
[Link] void start()
Starts the thread in a separate path of execution, then invokes the run() method
on this Thread object.
2. public void run()
If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
[Link] final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
[Link] final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
[Link] final void join(long millisec)
The current thread invokes this method on a second thread, causing the current
thread to block until the second thread terminates or the specified number of
milliseconds passes.
[Link] void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any
reason.
[Link] final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been
started but before
[Link] suspend()
It is used to suspend the thread.
[Link] resume()
It is used to resume the suspended thread.
[Link] stop() It is used to stop the thread.
Priority of a Thread (Thread Priority)
Each thread has a priority. Priorities are represented by a number between 1 and
10. In most cases, the thread scheduler schedules the threads according to their
priority (known as preemptive scheduling). But it is not guaranteed because it
depends on JVM specification that which scheduling it chooses. Note that not
only JVM a Java programmer can also assign the priorities of a thread explicitly
in a Java program.
Setter & Getter Method of Thread Priority
public final int getPriority(): The [Link]() method
returns the priority of the given thread.
public final void setPriority(int newPriority): The
[Link]() method updates or assign the priority of the thread
to newPriority. The method throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
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 PRIORITY
class PriorityE extends Thread{
public void run(){
[Link]([Link]().getName());
[Link]([Link]().getPriority());
class PE{
public static void main(String[] args){
PriorityE t1=new PriorityE();
PriorityE t2=new PriorityE();
PriorityE t3=new PriorityE();
[Link]("t1 thread");
[Link]("t2 thread");
[Link]("t3 thread");
[Link]();
[Link]();
[Link]();
}
EXAMPLE-2
class PriorityE extends Thread{
public void run(){
[Link]([Link]().getName());
[Link]([Link]().getPriority());
class PE{
public static void main(String[] args){
PriorityE t1=new PriorityE();
PriorityE t2=new PriorityE();
PriorityE t3=new PriorityE();
[Link]("t1 thread");
[Link]("t2 thread");
[Link]("t3 thread");
[Link](2);
[Link](6);
[Link](10);
[Link]();
[Link]();
[Link]();
What is [Link]()?
The [Link]() method is a static method of the Thread class that causes the
currently executing thread to sleep (pause its execution) for a specified number
of milliseconds.
EXAMPLE……
class multiplethread extends Thread{
public void run(){
String n=[Link]().getName();
try{
for(int i=1;i<=3;i++){
[Link](n);
[Link](3000);
}}
catch(InterruptedException i){
class multi1
public static void main(String[] args){
multiplethread t1=new multiplethread();
multiplethread t2=new multiplethread();
multiplethread t3=new multiplethread();
[Link]("thread 1");
[Link]("thread 2");
[Link]("thread 3");
[Link]();
[Link]();
[Link]();
String n=[Link]().getName();
[Link](n);}
SUSPEND() & RESUME() METHOD
suspend(): The main purpose of supend method is to put the thread
from running state to waiting state.
ex->A t1=new A();
A t2=new A();
A t3=new A();
[Link]();
[Link]();
[Link]();
[Link]();
resume():-Resume method is used to resume a suspended thread from
waiting to runnable state.
ex->[Link]();
class multiplethreadsuspend extends Thread{
public void run(){
String name=[Link]().getName();
for(int i=1;i<=3;i++){
[Link](name);
public static void main(String[] args){
multiplethread t1=new multiplethread();
multiplethread t2=new multiplethread();
multiplethread t3=new multiplethread();
[Link]("dada");
[Link]("viru");
[Link]("cheeku");
[Link]();
[Link]();
[Link]();//pause
[Link]();
//[Link](); //restart
Stop() method
stop():-stop is a method of a thread class which is used to terminate
a thread permanently.
Syntax:
[Link]();
[Link]();
[Link]();
[Link]();
Synchronization->
Synchronization is a technique through which we can control multiple thread or
among number of thread only one thread will enter inside the synchronized area
Types of Synchronization
There are the following two types of synchronization:
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Need of Thread Synchronization?
When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues. For example, if multiple
threads try to write within a same file then they may corrupt the data because one
of the threads can override data or while one thread is opening the same file at
the same time another thread might be closing the same file..
[Link] Synchronization
There are two types of thread synchronization in Java: mutual exclusive and inter-
thread communication.
[Link] Exclusive
[Link] method.
[Link] block.
[Link] synchronization.
[Link] (Inter-thread communication in Java)
[Link] method.
n Java, you can declare entire methods as synchronized which prevent multiple
threads from accessing the method simultaneously. With this, synchronization
becomes a simpler process because the mechanism is applied to all invocations
of the synchronized method automatically.
Example Synchronized method.
class Table {
// Method to print the table, not synchronized
synchronized void printTable(int n) {
for(int i = 1; i <= 5; i++) {
// Print the multiplication result
[Link](n * i);
try {
// Pause execution for 400 milliseconds
[Link](400);
} catch(Exception e) {
// Handle any exceptions
[Link](e);
class MyThread1 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
// Run method to execute thread
public void run() {
// Call printTable method with argument 5
[Link](5);
}
class MyThread2 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread2(Table t) {
this.t = t; // this keyword can be used to refer the current object in a
//method or constructor.
// Run method to execute thread
public void run() {
// Call printTable method with argument 100
[Link](100);
public class Main {
public static void main(String args[]) {
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2 objects with the same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
[Link]();
[Link]();
}
[Link] block.
Points to Remember
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
A Java synchronized block doesn't allow more than one JVM, to provide access
control to a shared resource.
The system performance may degrade because of the slower working of
synchronized keyword.
Java synchronized block is more efficient than Java synchronized method.
Example of Synchronized block.
class Table
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}//end of the method
//Creating Thread Class to call method
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
public void run(){
[Link](5);
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
public void run(){
[Link](100);
}
//Creating Main class to start threads
public class Main{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
[Link] Synchronization
If you make any static method as synchronized, the lock will be on the class not
on object.
Problem without static synchronization
Suppose there are two objects of a shared class (e.g. Bank) named object1 and
object2. In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock. But there can be interference between t1
and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.
We don't want interference between t1 and t3 or t2 and t4. Static synchronization
solves this problem.
class Bank extends Thread{
int bal=5000;
int withdraw;
Bank(int withdraw){
[Link]=withdraw;
public synchronized void run(){
String name=[Link]().getName();
if(withdraw<=bal)
[Link](name+"withdraw money");
bal=bal-withdraw;
else{
[Link]("insufficient balance");
class Customer
public static void main(String[] args){
Bank obj=new Bank(5000);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
[Link]("raju");
[Link]("shayam");
Bank obj2=new Bank(5000);
Thread t3=new Thread(obj2);
Thread t4=new Thread(obj2);
[Link]("rahul");
[Link]("manish");
[Link]();
[Link]();
[Link]();
[Link]();
Output.
rajuwithdraw money
rahulwithdraw money
insufficient balance
insufficient balance
Example of Static Synchronization
class Bank extends Thread{
static int bal=5000;
static int withdraw;
Bank(int withdraw){
[Link]=withdraw;
public static synchronized void withdraw(){
String name=[Link]().getName();
if(withdraw<=bal)
[Link](name+"withdraw money");
bal=bal-withdraw;
else{
[Link]("insufficient balance");
public void run()
withdraw();
class Customer
public static void main(String[] args){
Bank obj=new Bank(5000);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
[Link]("raju");
[Link]("shayam");
Bank obj2=new Bank(5000);
Thread t3=new Thread(obj2);
Thread t4=new Thread(obj2);
[Link]("rahul");
[Link]("manish");
[Link]();
[Link]();
[Link]();
[Link]();
Output..
rajuwithdraw money
insufficient balance
insufficient balance
insufficient balance
[Link] (Inter-thread communication in Java)
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is
paused running in its critical section and another thread is allowed to enter (or
lock) in the same critical section to be [Link] is implemented by following
methods of Object class:
[Link]()
[Link]()
[Link]()
1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception
Method
public final void wait()throws InterruptedException
Description
It waits until object is notified.
Method
public final void wait(long timeout)throws InterruptedException
Description
It waits for the specified amount of time.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
Difference between wait and sleep?
Wait() sleep()
[Link] wait() method releases the lock. 1. The sleep() method doesn't release the
lock.
[Link] is a method of Object class 2. It is a method of Thread class
[Link] is the non-static method [Link] is the static method
[Link] should be notified by notify() or notifyAll() methods [Link] the specified
amount of time, sleep is completed.
Example inter thread communicaton
class TotalEarnings extends Thread
int total=0;
public void run(){
synchronized(this){
for(int i=1;i<=10;i++){
total=total+100;
[Link]();
class MovieBookApp {
public static void main(String[] args) throws InterruptedException{
TotalEarnings te=new TotalEarnings();
[Link]();
synchronized(te){
[Link]();
[Link]("totalearning : " + [Link] + "rs");
FILE HANDLING: JAVA I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java's I/O (Input/Output) system is used to handle data reading and writing, both
from files and other data sources like network connections. The [Link] package
contains all the classes required for input and output operations.
Core Concepts of Java I/O
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. There are two main types:
[Link] Streams:
Handle binary data. They are useful for all types of I/O, such as reading and
writing image files.
Examples: InputStream, OutputStream, FileInputStream, FileOutputStream.
[Link] Streams:
Designed for handling character data (text). They automatically handle character
encoding.
Examples: Reader, Writer, FileReader, FileWriter.
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
1) [Link]: standard output stream
2) [Link]: standard input stream
3) [Link]: standard error stream
Let's see the code to print output and an error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
Let's see the code to get input from console..
1. int i=[Link]();//returns ASCII code of 1st character
2. [Link]((char)i);//will print the character
OutputStream Vs. InputStream
InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
OutputStream
Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
Java I/O Classes
Java provides a rich set of classes for performing I/O operations. Some of the key
classes include:
InputStream and OutputStream: These abstract classes form the foundation
for byte-oriented I/O operations. They provide methods for reading and writing
bytes from/to various sources and destinations.
Reader and Writer: These abstract classes are used for character-based I/O
operations. They provide methods for reading and writing characters from/to
character-based streams.
FileReader and FileWriter: These classes enable reading from and writing to
files using character-oriented operations.
FileInputStream and FileOutputStream: These classes allow reading from and
writing to files in a byte-oriented manner.
BufferedInputStream and BufferedOutputStream: These classes provide
buffering capabilities, which can significantly improve I/O performance by
reducing the number of system calls.
BufferedReader and BufferedWriter: These classes offer buffered reading and
writing of character data, enhancing I/O efficiency when working with character-
based streams.
File handling methods:-
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
Create new file
import [Link].*;
class createFile {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Users\\Naved\\OneDrive\\Desktop\\[Link]");
if([Link]()){
[Link]("file created");
else{
[Link]("file exist...");
Use file handling methods when file exists
import [Link].*;
class fileInfo {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Users\\Naved\\OneDrive\\Desktop\\[Link]");
if([Link]()){
[Link]("file name: "+[Link]());
[Link]("file name: "+[Link]());
[Link]("file name: "+[Link]());
[Link]("file name: "+[Link]());
[Link]("file name: "+[Link]());
[Link]("file name: "+[Link]());
else{
[Link]("file does'not exist...");
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.
EXAMPLE
import [Link].*;
class File_write
{
public static void main(String arg[])throws IOException
FileOutputStream fout=new FileOutputStream("[Link]");
//FileWriter fout=new FileWriter("C:\\Users\\Naved\\[Link]");
String s="welcome to java classes ";
byte b[]=[Link]();
[Link](b);
[Link]("succes----");
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
EXAMPLE
import [Link];
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("C:\\Users\\Naved\\[Link]");
int i=[Link]();
[Link]((char)i);
[Link]();
}catch(Exception e){[Link](e);}