0% found this document useful (0 votes)
8 views24 pages

Java Multithreading Basics Guide

The document provides a comprehensive overview of multithreading in Java, explaining concepts such as threads, processes, and the implementation of threads using both the Thread class and the Runnable interface. It covers key methods for managing threads, synchronization, and the differences between wait and sleep methods. Additionally, it includes examples of code to illustrate the concepts discussed.

Uploaded by

shriyadixit92
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views24 pages

Java Multithreading Basics Guide

The document provides a comprehensive overview of multithreading in Java, explaining concepts such as threads, processes, and the implementation of threads using both the Thread class and the Runnable interface. It covers key methods for managing threads, synchronization, and the differences between wait and sleep methods. Additionally, it includes examples of code to illustrate the concepts discussed.

Uploaded by

shriyadixit92
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Multi threading using JAVA

___________________________________________________________________________________
Q. What is thread?
____________________________________________________________________
Thread is a sub part of process or it is light weight process.

Q. What is process?
____________________________________________________________________________________
Process is running program ram or program in execution called as process.

Q. What is multi threading?


____________________________________________________________________
Multi threading means to execute the multiple threads simultaneously in waiting of each other by the
processor called as multi threading or In short we can say multithreading means to utilize the
idle/waiting period of process called as multi threading.

Note: Threading is not concept of JAVA basically it is concept of operating system and Java provides API
for implement thread.
Means we can say Java is language to provide platform for implement thread.

How many ways to implement thread using JAVA?


______________________________________________________________________
There are two ways to implement thread in JAVA

1) By Using Thread class


2) By using Runnable interface

How to create Thread by using Thread class


______________________________________________________________________________
If we want to implement the thread using Thread class we have some following steps.
1. Add [Link] package in application
____________________________________________________________________
import [Link].*;
Note: if we think about lang package it is default of package means we not need to import it.
2. Create user defined class and inherit Thread class in it.
________________________________________________________________________
We have one inbuilt class name as Thread and when we inherit the Thread class in any other or user
defined class then user defined class work as thread class.

Syntax: class classname extends Thread{


}
Example: class MyThread extends Thread{
}
Note: if we think about above code all properties of Thread class transfer in MyThread means here we
can say MyThread work as Thread
3. Override run() method of Thread class and write thread logics
_______________________________________________________________________
run() method is member of Runnable interface and Thread is implementer class of Runnable interface
and run() specially design for execute the thread logics or write thread logics.
Means In Short we can say Thread class work as Adapter between user define class and Runnable
interface.

Important points related with Runnable interface


_______________________________________________________________________
a. Runnable is functional interface in JAVA
b. Runnable interface known as Marker interface in JAVA
c) It is parent of Thread and provide run () method writing thread logics
d) Runnable especially design for implement thread using multiple inheritance.

Example with source code


import [Link].*;
// MyThread is Thread in program
class MyThread extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{
[Link]("I=%d\n",i);
}
}
}
public class MyThreadApp
{ public static void main(String x[])
{

}
}
4. Create Object of Thread child class and use its method to control or manage thread.
______________________________________________________________________________
If we think about manage the thread we have some methods provided by Thread class for manage the
thread.
void start(): this method is used for start the thread means when we call this() method then internally
JVM call run() method means we not need to call run() method manually because it is call by JVM
internally when we call start method.
Note: when we call run() method without start then run() method work like as normal overridden
method.

static void sleep(int milliseconds): this method is used for hold the thread execution for specified time
period
void stop(): this method can terminate the thread or destroy the thread.
boolean isAlive(): this method can check your thread running or not if thread is running return true
otherwise return false.
void join(): this method can hold other thread execution whenever running thread is not completed.
void setPriority(int priority): this method can set the execution priority of thread.
int getPriority(): this method can return priority of thread.
void setDaemon(boolean): this method can create user define thread as daemon thread when we set
true then we can mark user defined thread as daemon
boolean isDaemon(): this method can return true if user thread is daemon thread otherwise return
false.
Some methods of object can use in thread
void notify() : this method can call waited thread in the form of Queue means first waiting thread call
first and call only one thread at time.
void notifyAll(): notifyAll() method can call waited thread at time in the form of last in first out.
void wait(): this method can hold thread execution in unconditional waiting format.
void wait(int): this method can hold thread execution in conditional waiting format.

Example of multi threading


import [Link].*;
// MyThread is Thread in program
class MyThread extends Thread
{ public void run()
{ try
{
for(int i=1; i<=5;i++)
{
[Link]("First Thread =%d\n",i);
sleep(10000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class MyThread1 extends Thread
{ public void run()
{ try
{
for(int i=1; i<=50;i++)
{ [Link]("Second Thread =%d\n",i);
sleep(1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}

public class MyThreadApp


{ public static void main(String x[])
{
MyThread m = new MyThread();
[Link](); //call run() internally
MyThread1 m1 = new MyThread1();
[Link]();
}
}

Note: we cannot create any program java without thread because in java every program contains one
default thread known as main thread shown in following code.
Note: main thread is created by JVM and call by JVM

Now we want to discuss about stop() method


__________________________________________________________________________________
stop() method is used for terminate the execution of thread.

import [Link].*;
// MyThread is Thread in program
class MyThread extends Thread
{ public void run()
{ try
{
for(int i=1; i<=5;i++)
{
[Link]("First Thread =%d\n",i);
if(i==3)
{ stop();
}
sleep(10000);

}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class MyThread1 extends Thread
{ public void run()
{ try
{
for(int i=1; i<=50;i++)
{ [Link]("Second Thread =%d\n",i);
sleep(1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}

public class MyThreadApp


{ public static void main(String x[])
{
MyThread m = new MyThread();
[Link](); //call run() internally

MyThread1 m1 = new MyThread1();


[Link]();
}
}
boolean isAlive(): this method is used for check thread is running or not if thread is running return true
otherwise return false.
void join(): this method can hold thread execution until whenever running thread not complete its
execution.

import [Link].*;
// MyThread is Thread in program
class MyThread extends Thread
{ public void run()
{ try
{
for(int i=1; i<=5;i++)
{
[Link]("First Thread =%d\t%b\n",i,isAlive());
if(i==3)
{ stop();
}
sleep(10000);

}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class MyThread1 extends Thread
{ public void run()
{ try
{
for(int i=1; i<=50;i++)
{ [Link]("Second Thread =%d\t%b\n",i,isAlive());
sleep(1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}

public class MyThreadApp


{ public static void main(String x[])throws InterruptedException
{
MyThread m = new MyThread();
[Link](); //call run() internally
[Link]();
[Link]("Now status of first thread is "+[Link]());
MyThread1 m1 = new MyThread1();
[Link]();
}
}
Q. What happen if we call run () method directly without start() method?
____________________________________________________________________________
When we call run () method directly without start () method then run() method not work as thread just
it work as normal method and execute the sequentially means just its behavior is normal overridden
method.

Synchronization and Asychronization


____________________________________________________________________________________

Q. What is synchronization and Asynchronization?


_____________________________________________________________________________________
Synchronization: synchronization means if two or more than two threads use the resource/object
sequentially one by one at time called as synchronization.
Asynchronization: Asynchronization means if two or more than two threads use the resource/object
simultaneously waiting of each other called as asynchronization.

Q. What is resource?
____________________________________________________________________________
Here Resource meaning object because if we think about computer system we have resources and
peripherals so here hardware known as peripherals like as Printer ,Scanner etc and RAM known as
resource and if we think object so object is part of RAM means if RAM is resource and object part of
RAM so object is also resource.

Working of asynchronization

Note: if we think about above code we can say it is implementation of asynchronization because we
have two thread object Two and three and we have one resource object name as Table and we share
Table object reference in both threads means in Two and in Three so here Thread object two and three
use the Table simultaneously waiting of each other so this behavior known as asynchronization

Example with source code for synchronization


class Table
{
synchronized void showTable(int x)
{
try{
for(int i=1; i<=10;i++)
{
[Link]("%d X %d =%d\n",i,x,i*x);
[Link](1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class Two extends Thread
{ Table table;
void setTable(Table table)
{ [Link]=table;
}
public void run()
{
[Link](2);
}
}
class Three extends Thread
{ Table table;
void setTable(Table table)
{ [Link]=table;
}
public void run()
{ [Link](3);
}
}
public class SyncAsyncApp
{ public static void main(String x[])
{ Table tt = new Table();//resource
Two tw = new Two(); //create first thread in program
[Link](tt); //allocate resource to thread or resource use by thread
[Link](); // call thread or start thread execution

Three th = new Three();//create second thread in program


[Link](tt); //allocate same resource to thread which is allocated to first thread i.e Two
[Link]();
}
}
wait(),notify() and notifyAll()
_________________________________________________________________________
wait(): wait method is used for hold thread execution for specified time period and it is method of
Object class and wait method can use in synchronized block.
There are two types of wait
__________________________________________________________________________
a) Conditional wait: Conditional wait means if thread waiting for specified time period and re-execute
self called as conditional wait.
Syntax: void wait(int milliseconds): set waiting period in milliseconds

Example with conditional wait


_______________________________________________________________________________
class Table
{
synchronized void showTable(int x)
{
try{
for(int i=1; i<=10;i++)
{
[Link]("%d X %d =%d\n",i,x,i*x);
if(i==5)
{ wait(60000);
}
[Link](1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class Two extends Thread
{
Table table;
void setTable(Table table)
{ [Link]=table;
}
public void run()
{
[Link](2);
}
}
class Three extends Thread
{
Table table;
void setTable(Table table)
{ [Link]=table;
}
public void run()
{
[Link](3);
}
}
public class SyncAsyncApp
{
public static void main(String x[])
{ Table tt = new Table();//resource
Two tw = new Two(); //create first thread in program
[Link](tt); //allocate resource to thread or resource use by thread
[Link](); // call thread or start thread execution

Three th = new Three();//create second thread in program


[Link](tt); //allocate same resource to thread which is allocated to first thread i.e Two
[Link]();
}
}
b) Unconditional wait: unconditional wait means if thread is in waiting and not re-execute self called as
unconditional waiting and if we want to re-execute the from unconditional wait we have two methods
notify() and notifyAll()

Syntax: void wait(): here we not specify the re-execution time for thread.

void notify(): this method is used for restart thread or recall thread those are in unconditional wait and
call only one thread at time in the form first in first out format.
void notifyAll(): this method can call all waited threads those are in unconditional wait in last in first out
format
Note: wait(),notify() and notifyAll() must be synchronized block.

Example of notify() and notifyAll()


import [Link].*;
class Table
{
synchronized void showTable(int x)
{
try{
for(int i=1; i<=10;i++)
{
[Link]("%d X %d =%d\n",i,x,i*x);
if(i==5)
{ wait();
}
[Link](1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
synchronized void recall()
{
try{
notifyAll();
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class Two extends Thread
{
Table table;
void setTable(Table table)
{ [Link]=table;
}
public void run()
{
[Link](2);
}
}
class Three extends Thread
{
Table table;
void setTable(Table table)
{ [Link]=table;
}
public void run()
{
[Link](3);
}
}
public class SyncAsyncApp
{
public static void main(String x[])
{ Table tt = new Table();//resource
Two tw = new Two(); //create first thread in program
[Link](tt); //allocate resource to thread or resource use by thread
[Link](); // call thread or start thread execution

Three th = new Three();//create second thread in program


[Link](tt); //allocate same resource to thread which is allocated to first thread i.e Two
[Link]();

do{
Scanner xyz =new Scanner([Link]);
String msg=[Link]();
if([Link]("restart"))
{ [Link]();
}
}while(true);
}
}
Q. What is difference between wait() and sleep()?
____________________________________________________________________________________
Wait Sleep
Wait() method of Object class from [Link] Sleep() is static method of Thread class
Wait() method can work in synchronized block Sleep() can work in synchronized as well as non
only synchronized block
Wait() method can use the conditional wait as well Sleep() method can use only conditional wait.
as unconditional wait

How to create thread using Runnable interface


_________________________________________________________________________________

Q. Why we need to create thread using Runnable interface if we have Thread class?
____________________________________________________________________________________
Some time if we want to create thread using Thread class with the help of inheritance and if there is
already another class get inherited then we cannot inherit thread class in that class where another class
get inherited because diamond problem occur or multiple inheritance situation may be occur so resolve
this problem we have solution for create thread known as Runnable interface.

Steps to implement thread using Runnable interface?


______________________________________________________________________________
1. Add [Link] package in application
import [Link].*;
Note: we not need to import [Link] package because it is default package of java.
2. Create class and implements Runnable interface in it.
___________________________________________________________________________
class ABC implements Runnable
{
}
3. Override its run () method
______________________________________________________________________
import [Link].*;
class ABC implements Runnable
{ public void run()
{
try{
for(int i=1; i<=5; i++)
{
[Link]("I = %d\n",i);
[Link](1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
4. Create Object of Runnable implementer class
_________________________________________________________________________
ABC a1 = new ABC();
5. Create object of Thread class and pass reference of Runnable implementer in thread construct
_________________________________________________________________________________
When we work with Runnable interface then we get only one method using that i.e run()
and run() method only help us to write logic of thread according to requirement of user but if we want
to start() thread or manage other thread activity then we do not have method in Runnable interface and
other method provide by Thread class so when we use Runnable interface for achieve thread we have to
use following constructor
Syntax: Thread(Runnable): if we think about this constructor it contain parameter name as Runnable
means here we have to pass reference of Runnable or its implementer class for start thread or perform
other operation on thread.
Means here we can say Thread(Runnable) constructor is implementation of loose coupling and dynamic
polymorphism

Example
A a1 = new A();
Thread t = new Thread(a1);

6. Start thread & use methods of thread for manage thread.

Example with source code


import [Link].*;
class ABC implements Runnable
{ public void run()
{
try{
for(int i=1; i<=5; i++)
{
[Link]("I = %d\n",i);
[Link](1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
public class ThreadWithRunnableApp
{ public static void main(String x[])
{ ABC a1 = new ABC();
Thread t1 = new Thread(a1);
[Link]();
}
}
Daemon thread concept
____________________________________________________________________________
Daemon thread is a service provider thread means those thread work in background as service provider
known as daemon thread.
Example: garbage collector is best example of daemon thread.
Note: user can mark own thread as daemon thread and for that we have following methods

void setDaemon(boolean): if we pass true value to this method then user can create own thread as
daemon thread
boolean isDaemon(): this method can check user thread is daemon or not if user thread is daemon
thread then return true otherwise return false.

Example:
class A extends Thread
{
public void run()
{
try{
for(int i=1;i<=10; i++)
{
[Link]("I = %d\n",i);
[Link](1000);
}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
public class TestDaemonApp
{
public static void main(String x[])
{ A a1 = new A();
[Link](true);
[Link]();
[Link]("Is User Thread is daemon "+[Link]());
}
}

Life cycle of Thread


___________________________________________________________________________
Life cycle of thread means process from thread creation to thread termination means to identity the
behavior of thread from creation to termination called as life cycle.

Stages of Thread life cycle


____________________________________________________________________________
1. New
2. Active
3. Blocked/Waiting
4. Timed Waiting
5. Terminated

Now we want to discuss about every steps.


New: whenever new thread is created it is always in new state means when your thread is in new state
then code of run() not executed.
When we create object of thread class by using new keyword know as new state of thread where thread
allocate memory but not execute code.

Active: when a invoke the start() method. it moves from new state to the active state. if we think about
active state it contain two states Runnable & Running
Runnable: A thread that is ready to run is then moved to the Runnable state. In the Runnable state may
be running or may be ready to run any given instance of time it is responsibility of thread scheduler to
provide thread time to run.

Running: When thread get CPU it move from Runnable to running state generally most common change
in state from Runnable to running and again back to Runnable

Blocked or Waiting state: whenever thread is inactive for span of time (not permanently) then either
the thread in block or waiting state.

Example: Suppose consider we have Thread A may want to print some data from printer However at the
same time the other thread e.g B using printer to print some data. In this case Thread A has wait for
Thread B to use print thus the Thread A in block state. The thread in the block state unable to perform
any execution never consumes CPU.
main thread invoke join() method then we can say main thread in waiting state means main thread wait
until child thread complete their task and suppose child thread complete their task then thread schedule
provide notification to main thread then main thread again change state from waiting to active state.
If there is multiple threads in waiting then thread scheduler has responsibility to decide which thread
take in active state

Timed waiting: Suppose consider we have two threads A and B if A is in waiting but not complete its
task then waiting of A Thread B can execute called as time waiting and example of time waiting is sleep()
method

Note: the major difference between blocked state and time waiting is
In Block state working thread not allow other thread whenever its task not completed even working
thread has some waiting period Example of block state is synchronization or join() method and in time
waiting state if working thread has some waiting period then other can execute and example of timed
waiting is sleep() method

Terminated State: when thread destroys called as termination state

Following scenario where thread can terminate.


____________________________________________________________________________

1. When thread finishes its job then it exists or terminates normally.

2. Abnormal Termination: when in thread execution unusual event occur like as run time exception or
segmentation fault etc

3. When user force fully terminate thread using stop() method


Now we want to discuss diagram of thread life cycle

How to implement the thread life cycle practically


______________________________________________________________________
class First extends Thread
{ Second second;
public void setSecond(Second second)
{ [Link]=second;
}
public void run()
{ try
{
for(int i=1; i<=5; i++)
{
sleep(1000);
if(i==2)
{ //stop();
join();
}
[Link]("Now second thread state "+[Link]());

}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
class Second extends Thread
{ First first;
public void setFirst(First first)
{ [Link]=first;
}
public void run()
{ try
{
for(int i=1; i<=5; i++)
{ [Link]("Now first thread state "+[Link]());

sleep(1000);

}
}
catch(Exception ex)
{ [Link]("Error is "+ex);
}
}
}
public class LifeCycleApp
{
public static void main(String x[])throws Exception
{
First first = new First();
Second second = new Second();

[Link]("First thread status "+[Link]());


[Link]("Second thread status "+[Link]());
[Link](first);
[Link](second);

[Link](); //active

[Link]();
}
}
How to use daemon thread practically or where daemon threads use
________________________________________________________________
If we think about real time scenario of daemon thread
a) Monitoring application & logging application for particular system

import [Link].*;
import [Link].*;
class Machine extends Thread
{
private String machineName;
private int capacity;

public void setMachineName(String name)


{ [Link]=name;
}
public String getMachineName()
{ return machineName;
}
public void setCapacity(int capacity)
{ [Link]=capacity;
}
public int getCapacity()
{ return capacity;
}
public void run()
{ [Link](capacity*2);
}
}
class MachineMonitorApp extends Thread
{ Machine m;
public void setMachine(Machine m)
{this.m=m;
}
public void run()
{
if([Link]()>100)
{
try{
FileWriter fw=new FileWriter("D:\\july 2024\\[Link]",true);
BufferedWriter bw=new BufferedWriter(fw);
[Link]("Machine "+[Link]()+" overloaded with "+[Link]());
[Link]();
[Link]();
[Link]();
}
catch(Exception ex)
{
}
}
}
}
public class ManuPlantApp
{
public static void main(String x[])
{
Machine m[]=new Machine[5];
for(int i=0;i<[Link];i++)
{ Scanner xyz = new Scanner([Link]);
[Link]("Enter machine name and capacity");
m[i]=new Machine();
m[i].setMachineName([Link]());
m[i].setCapacity([Link]());
m[i].start();
MachineMonitorApp monitor=new MachineMonitorApp ();
[Link](true);
[Link](m[i]);
[Link]();
}
}
}

Thread priority concept


_________________________________________________________________________
Thread priority means to decide execution priority of thread means when which thread should start
If we think about thread priority we have three types of thread priority and for that purpose
Thread provide three constant values to us and these the internally integer variable with final and static
modifier means they have fixed values and we cannot modify

There are three priorities in Thread


___________________________________________________________________________
1. MIN Priority : for min priority default value is 1 and static variable for that priority is
public static final int MIN_PRIORITY=1;
2. MAX Priority: MAX_PRIORITY default value is 10 and static variable for that priority is
public static final MAX_PRIORITY=10
3. NORM Priority: NORM_PRIORITY default value is 5 and static variable that priority is
public static final NORM_PRIORITY=5 and every thread has default priority known as normal priority.

Note: thread priority implementation may be change OS to Os because OS own thread priority policy
and java priority may be difference so thread priority may be work different on every OS

class First extends Thread


{
public void run()
{
[Link]([Link]()+"\t"+[Link]());
}
}
public class PriorityApp
{
public static void main(String x[])
{
First f1=new First();
First f2 = new First();
First f3 = new First();
[Link](2);
[Link](8);
[Link](6);

[Link]();
[Link]();
[Link]();
}
}
//Executer services and Thread concurrency API
// thread pooling and
//volatile

You might also like