Multi Threading Notes and Interview Questions
Multi Threading Notes and Interview Questions
Multi Threading Notes and Interview Questions
Multitasking
The process of performing more than one task at a time is called multitasking.
➢ We have two types of multitasking
• Process based multitasking
• Thread based multitasking
Process based multitasking
➢ The process of executing more than 1 task at a time where each task is independent
of each other (Each task is an individual process ) is called process based multitasking.
➢ These type of multitasking is suitable at OS level.
Thread based multitasking
➢ The process of executing more than 1 task at a time where each task is an individual
unit of the same process (same program ) is called as thread based processing.
➢ It is suitable at the application level.
Thread
Thread is smallest unit/part of a program .In programming language thread is nothing but
the flow of execution of a program.
Multi threading
➢ The process of executing a program by using more than one thread is called as
multithreading.
➢ Multi threading is used to increase the efficiency of an application by reducing the
response time.
➢ Multithreading can be used in servers to reduce the response time.
Current Thread()
➢ It is static native method present in thread class.
MARUTHI CHARAN TEJ 1
➢ It will return the reference of currently executing thread object.
➢ The return type of this method is thread.
Example program to understand CurrrentThread() and Sleep()
public class ToUnderstandCurrentThreadAndSleep {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000);
System.out.println(i + " Printed by " + Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Runnable
➢ It is a functional interface present in java.lang.package
➢ This interface has to be implemented by all the classes which should extend the
behaviour of a thread.
➢ This interface have a method run() in which we can write the instruction that has to
be executed by the thread.
e.printStackTrace();
}
if(i%2!=0) {
System.out.println(i);
}
}
}
}
Thread priorities
➢ It is used to decide the importance that has to be given for a thread to execute a
program.
➢ Thread scheduler will allocate the processor for a thread based on the thread priority.
➢ A thread can have a priority in the range of 1 to 10, where 1 is the minimum and 10 is
the maximum priority.
➢ We can set the priority for a thread by calling set priority (int) and we can get priority
of a thread by calling get priority ().
• Thread.MIN_PRIORITY→1
• Thread.MAX_PRIORITY→10
• Thread.NORM_PRIORITY→5
Note :
➢ The default priority of the main thread is 5.
➢ The default priority of a thread will be same as its parent Thread.
Example :
public class DisplayPriority {
public static void main(String[] args) {
System.out.println("Minimum Priority " + Thread.MIN_PRIORITY);
System.out.println("Maximum Priority " + Thread.MAX_PRIORITY);
System.out.println("Normal Priority " + Thread.NORM_PRIORITY);
}
}
Program to understand the thread priority
public class MyThread extends Thread {
public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println("hii: Printed by:" + Thread.currentThread());
}
}
}
Join()
➢ It is a non-static method present in Thread class .
➢ This method is overloaded
➢ If we call join() on a thread then that thread will wait for another thread to join it ,
to continue its execution.
➢ We might get interrupted Exception when we can call join() .
➢ Following are the overloaded join() methods.
• Join()
• Join(Long)
• Join(Long, int)
Impact of join on Thread life cycle
➢ Whenever we can call join() on a thread the Thread will go to waiting state and it will
wait for the other thread to join to continue its execution.
t.start() Run()
New/born Runnable Running Execution of run() over
state state state
Dead state
T1.join()
Waiting
state
Has-A-Relationship
➢ A relationship exist such that one object depending upon anther object is called as
has-a-relationship.
➢ We have 2 types of has-A-Relationship.
• Composition
• Aggregation
Composition
If has-A-Relationship exists such that one object cannot exist without depending on another
object is called as composition.
Example: car→engine , human→Brain, Human→Heart
composition
Start()
Car Engine
Example
public class Engine {
public void start() {
System.out.println("Engine is started");
}
}
Brand; Number
Cost; Sp
Display(); Display
Insert sim1(simcard)
Insert sim2(simcard)
Remove sim1()
Remove sim2()
Check availability()
Lock
➢ Lock is a mechanism used in java which is used to make an object/resource
threadsafe.
➢ We can use 2 types of lock to make a resource threadsafe.
• Class Level lock
• Object Level lock
Class level lock
➢ It is a unique lock given for every class which is required for a thread in order to
access the static data of a resource.
➢ A thread must acquire class-level lock in order to execute the static synchronized
methods of a class.
➢ Once a thread acquires class level lock it can access all the static data of the class .And
it can also execute the static synchronized methods.
Example:
public class Display {
public void test() {
System.out.println("Hii from test()");
synchronized (Display.class) {
//A thread must acquire the class level lock to execute this area
}
System.out.println("Byee from test()");
}
}
Object level lock
➢ It is a lock that has to be acquired by a thread in order to execute the non-static data
of a resource.
➢ Every object will have a unique lock and it is called as Object level lock.
➢ If a thread acquires the object level lock ,it can execute all the non-static methods of
a class.
Synchronized statements
➢ The statements which are written inside the synchronized method (or) synchronized
block are called as synchronized statement .
➢ A thread must acquire the lock in order to execute the synchronized statements.
Code to achieve synchronization by using synchronized block
public class SynchronizedTable {
public void printTable(int n) {
System.out.println("Started printing :" + n + " table");
synchronized (this) {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(n + "*" + i + "=" + (n * i));
}
}
System.out.println("finished printing"+n+"table");
}}
public class MyThreadSyn extends Thread{
SynchronizedTable t;
int n;
public MyThreadSyn(SynchronizedTable t, int n) {
super();
this.t = t;
this.n = n;
}
public void run() {
t.printTable(n);
}
}
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "has locked" +
res1);
synchronized (res2) {
System.out.println(res1 + res2);
}
}
};
Runnable r2 = () -> {
synchronized (res2) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "has locked" +
res1);
synchronized (res1) {
System.out.println(res1 + res2);
}
}
};
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();t2.start();
}}
➢ In the above example t1 has locked resources and t2 has locked resource2. T1
requires the lock of resource2 to continue the extension ,it will release the lock of
Notify()
➢ It is a method present in object class.
➢ It is used to notify a thread which is waiting to acquire the lock of the resource.
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.suspend();
System.out.println("Thread suspended");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.resume();
System.out.println("Thread resumed");
}
}
➢ By extending the Thread class, we cannot extend any other class, as Java does not
allow multiple inheritances while implementing the Runnable interface; we can also
extend other base class(if required).
➢ By extending the Thread class, each of thread creates the unique object and associates
with it while implementing the Runnable interface; multiple threads share the same
object
➢ Thread class provides various inbuilt methods such as getPriority(), isAlive and many
more while the Runnable interface provides a single method, i.e., run().
Is it
NO YES YES
overloaded?
Is it final? NO YES NO
sleep(long ms)-
>native & sleep (long
Is it native? YES NO
ms, int ns)-> non
native
No, if you do so, it will throw IllegalThreadStateException. Therefore, we can only create a
daemon thread before starting the thread.
1. class Testdaemon1 extends Thread{
2. public void run(){
3. System.out.println("Running thread is daemon...");
4. }
5. public static void main (String[] args) {
6. Testdaemon1 td= new Testdaemon1();
7. td.start();
8. setDaemon(true);// It will throw the exception: td.
9. }
10.}
Synchronization is the capability to control the access of multiple threads to any shared
resource. It is used:
1. To prevent thread interference.
2. To prevent consistency problem.
When the multiple threads try to do the same task, there is a possibility of an
erroneous result, hence to remove this issue, Java uses the process of synchronization which