Multi Threading Notes and Interview Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Multi threading

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.

Java. lang. thread


➢ It is a class which will help the JVM to execute a program in more than one thread
concurrently.
➢ To execute a java program parllely in more than one flow.
➢ Following are the important methods presents in thread class
• Sleep(long)
• Sleep(long, int)
• Yield()
• Join()
• Current Thread()

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.

Ways to create a thread


➢ We can create a thread in java in 2 ways
• By extending Thread class
• By Implementing Runnable interface

Creating a thread by extending thread class


public class _02_CreatingThreadByExtendingThreadClass extends Thread {
public void run() {
for (int i = 1; i <= 20; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {

e.printStackTrace();
}
if(i%2!=0) {
System.out.println(i);
}
}
}
}

public class _03_PrintEvenAndOddByUsingExtendingThreadClass {


public static void main(String[] args) throws InterruptedException {
_02_CreatingThreadByExtendingThreadClass t = new _02_CreatingThreadByExtendingThreadClass();
t.start();// initialize and starts the thread
for (int i = 0; i <= 20; i++) {
Thread.sleep(500);
if (i % 2 == 0) {
System.out.println(i);

MARUTHI CHARAN TEJ 2


}
}
}}

Creating a thread by creating a Runnable interface


public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Hii");
}
}
}

public class TestMyRunnabele {


public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
for (int i = 0; i <= 10; i++) {
System.out.println("hello");
}
}
}

Setting and Getting name of a Thread


❖ setName(String)
➢ It is a non-static method present in Thread class.
➢ It is used to set the name for the thread.
❖ getName()
➢ It is a non-static method present in ThreadClass
➢ It is Used to get the name of a Thread.

Example program to understand getName and SetName


public class PrintTable implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(5 + "*" + i + "=" + (i * 5) + " Printed by" +
Thread.currentThread().getName());
}
}
}

public class TestPrintTable {


public static void main(String[] args) {
PrintTable r = new PrintTable();
Thread t = new Thread(r);
t.setName("5th");
t.start();
Thread.currentThread().setName("7th");
for (int i = 1; i <= 10; i++) {

MARUTHI CHARAN TEJ 3


System.out.println(7 + "*" + i + "=" + (i * 7) + "Printed by" +
Thread.currentThread());
}
}
}

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());
}
}
}

public class TestPriority {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("T1");
t1.setPriority(8);
System.out.println("T1 priority :" + t1.getPriority());
MyThread t2 = new MyThread();
t2.setName("T2");

MARUTHI CHARAN TEJ 4


t2.setPriority(4);
System.out.println("T2 priority :" + t2.getPriority());
MyThread t3 = new MyThread();
t3.setName("T3");
t3.setPriority(4);
System.out.println("T3 priority :" + t3.getPriority());
t1.start();
t2.start();
t3.start();
// t1.start();//Illegal Threadstate Exception
}
}
Note :
➢ If we try to set the priority for a thread which is greater than 10 and less than 1we
will get illegal Argument Exception.
➢ If we try to call Start() on a thread which is already started then we will get illegal
Thread State Exception.
Thread life cycle
➢ Thread lifecycle depicts the different states of a thread from Born state to Dead state.
Following are the different states of a Thread life cycle.
• New/Born state
➢ A thread is said to be new(or) born as soon as we create an object of the class.
• Runnable state
➢ A thread is said to be in runnable state once we call the start().
• Running state
➢ A thread is said to be in running , once the run() is called Running state.
• Sleep state
➢ A thread will be there in sleeping state once the sleep() is called as Sleep state.
• Dead state
➢ A thread will die once the execution of run() is over and it will go to Dead state.

MARUTHI CHARAN TEJ 5


Prevention of thread Execution
➢ We can prevent a thread execution by calling the following methods.
✓ Sleep(long)
✓ Sleep(long,int)
✓ Yield()
✓ Join()
✓ Join(long)
Yield()
➢ It is a static method present in java.lang Thread class.
➢ Yield() will cause the current executing thread to pause its execution and provide the
chance for other waiting threads of the same priority.
➢ Thread scheduler might ignore the instruction of yield()
➢ If there is no waiting thread with the same priority then the current thread will
continue its execution.

public class MyThread extends Thread {


public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println("hii: Printed by:" + Thread.currentThread());
}
}
}

MARUTHI CHARAN TEJ 6


public class TestYield {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("T1");
t1.setPriority(1);
System.out.println("T1 priority :" + t1.getPriority());
MyThread t2 = new MyThread();
t2.setName("T2");
t2.setPriority(1);
System.out.println("T2 priority :" + t2.getPriority());
MyThread t3 = new MyThread();
t3.setName("T3");
t3.setPriority(5);
System.out.println("T3 priority :" + t3.getPriority());
t1.start();
t2.start();
t3.start();
t1.yield();
for (int i = 1; i <= 5; i++) {
System.out.println("hiiiiii");
}
}
}

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

MARUTHI CHARAN TEJ 7


Example program to understand JOIN() No argument
public class JoinDemo extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hii from :" + Thread.currentThread().getName());
}
}
}

public class TestJoinDemo {


public static void main(String[] args) throws InterruptedException {
JoinDemo t1 = new JoinDemo();
t1.start();
t1.setName("join Demo");
t1.join();
for (int i = 1; i <= 10; i++) {
Thread.sleep(500);
System.out.println("hii from : " + Thread.currentThread().getName());
}}}
Example program to understand join(Long)
public class TestJoin {
public static void main(String[] args) throws InterruptedException {
JoinDemo t1 = new JoinDemo();
JoinDemo t2 = new JoinDemo();
JoinDemo t3 = new JoinDemo();
t1.start();
t1.join(2000);// main thread will wait for 2 seconds for t1
t2.start();
t2.join(2000);// main thread will wait for 2 seconds for t1
t3.start();
}
}

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

MARUTHI CHARAN TEJ 8


Aggregation
If has-A-Relationship exists such that ,an object can exists without depending on another
object is called as Aggregation
Example: car→Music System, smartphone →simcard
Note :
We can achieve Has-A-Relationship in java by declaring the reference of one object inside
another object.
Let us consider 2 objects car and Engine we need to establish the Has-A-Relationship
between car and Engine.
➢ To establish Has-A-Relationship between car and Engine ,we need to declare the
reference of engine in car.

composition

Start()

Car Engine

Example
public class Engine {
public void start() {
System.out.println("Engine is started");
}
}

public class Car {


private Engine e = new Engine();
public Engine getE() {
return e;
}
public void setE(Engine e) {
this.e = e;
}
}

➢ In java we can achieve Has-A-Relationship in 2 Ways


• Early instantiation
• Lazy instantiation

MARUTHI CHARAN TEJ 9


Early instantiation
➢ When we create an object of depending class , if the dependent class object created
implicitly then that type of instantiation is called Early instantiation.
➢ The above Engine-car classes are the example of early instantiation.
Lazy instantiation
When we create the depending class object ,if only the depending class object is created
and the dependent object has to be injected using the helper method ,that type of
instantiation is called as lazy instantiation.
Example program to understand Lazt instantiation

Brand; Number
Cost; Sp

Display(); Display
Insert sim1(simcard)
Insert sim2(simcard)
Remove sim1()
Remove sim2()
Check availability()

Smart phone Sim card


Code
public class SimCard {
long number;
String sp;
public SimCard(long number, String sp) {
this.number = number;
this.sp = sp;
}
public void display() {
System.out.println("SimCard Name: " + number);
System.out.println("Service provider: " + sp);
}
}

public class SmartPhone {


String brand;
double cost;

MARUTHI CHARAN TEJ 10


SimCard sim1;
SimCard sim2;

public SmartPhone(String brand, double cost) {


this.brand = brand;
this.cost = cost;
}

public void display() {


System.out.println("Brand :" + brand);
System.out.println("Cost :" + cost);
if (sim1 != null) {
System.out.println("Details of simcard1");
sim1.display();
}
if (sim2 != null) {
System.out.println("Details of simcard2");
sim2.display();
}
}

public void insertsim1(SimCard sim1) {


if (this.sim1 != null) {
System.out.println("Slot already occupied");
} else {
this.sim1 = sim1;
}
}

public void insertsim2(SimCard sim2) {


if (this.sim2 != null) {
System.out.println("Slot already occupied");
} else {
this.sim2 = sim2;
}
}

public void removesim1() {


sim1 = null;
System.out.println("sim1 is removed");
}

public void removesim2() {


sim2 = null;
System.out.println("sim2 is removed");
}

public void checkAvailability() {


if (sim1 == null && sim2 == null) {
System.out.println("Both slots are empty");
} else if (sim1 == null && sim2 != null) {
System.out.println("1st slot is Empty");
} else if (sim1 != null && sim2 == null) {
System.out.println("2nd slot is empty");
} else {
System.out.println("both the slots are occupied");
}}}
public class Test {
public static void main(String[] args) {
SmartPhone s = new SmartPhone("samsung", 25000);
s.checkAvailability();
s.insertsim1(new SimCard(98797927, "jio"));

MARUTHI CHARAN TEJ 11


s.checkAvailability();
s.insertsim2(new SimCard(767767, "Airtel"));
s.checkAvailability();
System.out.println();
System.out.println("Before removing the simcard");
s.display();
s.removesim1();
s.checkAvailability();
s.removesim2();
s.display();
}
}
Race condition /Data Inconsistency
➢ It is a condition where we will get the inconsistent data when more than one thread
is trying to access a resource at a time. This condition is called as data
Inconsistency/race condition.
➢ We can overcome this problem by making the resources thread safe.
➢ We can make a resource thread safe by the following ways
• By making synchronized method
• By making synchronized block
Synchronized
➢ It is a keyword in java
➢ It is a modifier in java.
➢ It is used to make a thread safe.
➢ If any method is prefixed with synchronized keyword it is called as synchronized
method and only thread can access that method at a time.
➢ If a block is prefixed with synchronized ,then that block will be called as synchronized
block. And only one thread can access the synchronized block at a time.
Example program to understand thread synchronization by using synchronized method
public class Table {
public synchronized void printtable(int n) {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(n + "*" + i + "=" + (n * i));
}}}

public class PrintTable extends Thread{


Table t;
int n;
public void run() {
t.printtable(n);
}
PrintTable(Table t, int n) {

MARUTHI CHARAN TEJ 12


this.n = n;
this.t = t;
}
}

public class Test {


public static void main(String[] args) {
Table t = new Table();
PrintTable t1 = new PrintTable(t, 5);
t1.start();
PrintTable t2 = new PrintTable(t, 5);
t2.start();
}
}

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.

MARUTHI CHARAN TEJ 13


public class DisplayObjectLevelLock {
public void test() {
System.out.println("Hii from test()");
synchronized (this) {
// A thread must acquire the object level lock to execute this area
}
System.out.println("Byee from test()");
}
}

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);
}
}

public static void main(String[] args) {


SynchronizedTable t = new SynchronizedTable();

MyThreadSyn t1 = new MyThreadSyn(t, 5);


MyThreadSyn t2 = new MyThreadSyn(t, 7);
t1.start();
t2.start();}}
Example program to create a thread by using Lambda Expression
public class CreateAThreadUsingLambdaExp {
public static void main(String[] args) {
Runnable r = () -> {
for (int i = 1; i <= 10; i++)
MARUTHI CHARAN TEJ 14
System.out.println(i);
};
Thread t=new Thread(r);
t.start();
}
}
Deadlock
➢ Deadlock is a situation where the threads will wait for each other to release the lock
of a resource.
➢ One thread will wait for another thread to release the lock of a resource and the
other thread will also do the same thing.
➢ This wait will continue forever and they will never got the lock of the resource ,and
this situation is called as Deadlock.
Example program to understand deadlock
public class DeadLockDemo {
public static void main(String[] args) {
final String res1 = "Room number 101";
final String res2 = "Room number 102";
Runnable r1 = () -> {
synchronized (res1) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {

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

MARUTHI CHARAN TEJ 15


resource1 only after getting lock of resource t2 require the lock of resource1 to
continue its execution and it will release the lock of resource2 only after getting the
lock of resource1.
➢ Now t1 will wait for t2 to release the lock of resources and t2 will wait for t1 to
release a lock of resources and this wait will continue forever resulting in deadlock.
Interthread communication/cooperation
➢ The process of synchronized threads communication with each other to access the
resources or to execute the instructions is called as interthread communication or co-
operation.
➢ When a threads accessing synchronized area by acquiring the lock of a resource and it
can release the lock temporarily so that other waiting threads get the chance to
access the synchronized block.
➢ A thread can also send a notification to the other waiting threads about releasing the
lock.
➢ Following are the methods which are present in java.lang.object using the threads
can communicate with each other.
✓ Wait()
✓ Wait(Long)
✓ Wait(Long,int)
✓ Notify()
✓ NotifyAll()
Wait()
➢ It is a method present in jav.lang.object class.
➢ When we call this method on a object,the current executing thread will go to waiting
state by releasing the lock of object .The other waiting thread will gets the chance to
acquire the lock of the object.
➢ The thread will which released the lock has to wait for the other thread to either call
notify() or notifyAll() in order to get the lock of the object.
➢ This method is overloaded
✓ Wait()
✓ Wait(Long)
✓ Wait(Long,int)

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.

MARUTHI CHARAN TEJ 16


➢ Once the notify() is called a waiting thread will get the chance to acquire the lock of
the resource.
NotifyAll()
➢ This method is present in object class.
➢ It is used to wakeup all the waiting threads on the object.
Program to understand interthread communication
public class Customer {
double balance = 10000;
public synchronized void withdraw(double amount) {
System.out.println("Trying to withdraw " + amount);
System.out.println("Available balance " + balance);
if (balance < amount) {
System.out.println("Waiting to deposit ");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance -= amount;
System.out.println(amount + "Withdrawn succesfully");
System.out.println("Available balance " + balance);
}
public synchronized void deposit(double amount) {
System.out.println("Depositing " + amount);
balance += amount;
System.out.println("Amount deposit succesfully");
System.out.println("Available balance :" + balance);
notify();
}
}

public class TestCustomer {


public static void main(String[] args) {
Customer c = new Customer();
Runnable r1 = () -> {
c.withdraw(15000);
};
Runnable r2 = () -> {
c.deposit(5000);
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}

MARUTHI CHARAN TEJ 17


Interview Questions
1)What is multitasking?
Answer will be at the top of the page1
2)What do you mean by a Multithreaded program?
A multithreaded program is a computer program that can run multiple threads of execution
concurrently. Threads are lightweight processes that can run independently of each other,
but they share the same memory space and other resources. This allows multithreaded
programs to take advantage of multiple processors or cores to improve performance.
Multithreading can be used to improve the performance of a program in a number of ways.
For example, it can allow a program to perform multiple tasks at the same time, such as
downloading a file while browsing the web. It can also allow a program to respond more
quickly to user input, such as in a game or a web application.
There are a number of different ways to implement multithreading in a computer program.
One common approach is to use a thread library, which provides a set of functions for
creating, managing, and synchronizing threads. Another approach is to use a threading
model, which provides a more abstract way of writing multithreaded programs.
Multithreading can be a complex and challenging technique to use, but it can also be a very
effective way to improve the performance of computer programs.
3)What is multithreading?
4) What are the advantages of multithreading?
• Performance: Multithreading can improve performance by reducing development
time.
• Coding: Multithreading can simplify and streamline program coding.
• Responsiveness: Multithreading can improve GUI responsiveness.
• Tasks: Multithreading can allow tasks to occur simultaneously and in parallel.
• Storage: Multithreading can improve the use of cache storage by utilizing resources.
• Maintenance: Multithreading can reduce the cost of maintenance.
• Throughput: Multithreading can increase the amount of work done by a program in a
given time.
• Concurrency: Multithreading can enhance concurrency on a multi CPU machine.
• Requests: Large or complex requests or slow clients don't block other requests for
service.

MARUTHI CHARAN TEJ 18


• Threads: The threads are independent, so it does not block the user to perform
multiple operations at the same time.
• Exceptions: If an exception occurs in a single thread, it does not affect other threads.

5)What are the two ways in which Thread can be created


• Extend the Thread class: Create a new class that extends the Thread class and create
an instance of that class.
• Implement the Runnable interface: Create a class that implements the runnable
interface.
6)What is a thread?
A thread is a lightweight subprocess. It is a separate path of execution because each thread
runs in a different stack frame. A process may contain multiple threads. Threads share the
process resources, but still, they execute independently.

7)Differentiate between process and thread?


A Program in the execution is called the process whereas; A thread is a subset of the process
➢ Processes are independent whereas threads are the subset of process.
➢ Process have different address space in memory, while threads contain a shared
address space.
➢ Context switching is faster between the threads as compared to processes.
➢ Inter-process communication is slower and expensive than inter-thread
communication.
➢ Any change in Parent process doesn't affect the child process whereas changes in
parent thread can affect the child thread.

MARUTHI CHARAN TEJ 19


8) Describe the life cycle of the thread?
9) Explain suspend() method under the Thread class.
The suspend() method in the Thread class is used to temporarily stop the execution of a
thread. When a thread is suspended, it is put into a waiting state and cannot continue
executing until it is resumed. The resume() method is used to resume the execution of a
suspended thread.
The suspend() and resume() methods are deprecated and should not be used in new
code. They are not reliable and can cause problems, such as deadlocks.
Here is an example of how to use the suspend() and resume() methods:
import java.lang.Thread;

public class Example {


public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("Hello, world!");
}
}
});

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");
}
}

MARUTHI CHARAN TEJ 20


10) Differentiate between the Thread class and Runnable interface for creating a Thread?
Thread class
A class that creates a new thread. Each thread has a unique object associated with it. The
Thread class has multiple methods, including start(), run(), setName(), and getName().
Runnable interface
An interface that allows many threads to share the same thread object. Multiple threads
share the same object, so require less memory. The Runnable interface only has one
abstract method.
Other differences:

➢ 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().

11) What does join(),wait(),sleep(),yield()method?


join()
The join() method waits for a thread to die. In other words, it causes the currently running
thread to stop executing until the thread it joins with completes its task.
wait()
The wait() method causes a thread to suspend its execution until it is notified by another
thread. The wait() method is typically used in conjunction with the notify() or notifyAll()
methods to coordinate access to shared resources.
sleep()
The sleep() method causes a thread to suspend its execution for a specified amount of time.
The sleep() method is typically used to cause a thread to wait for a specific amount of time
before continuing to execute.
Property yield() join() sleep()

If a thread wants to If a thread does not


If a thread wants to
pass its execution to want to perform any
wait until completing
give chance to operation for a
Purpose of some other thread
remaining threads of particular amount of
then we should go
the same priority then time, then it goes for
for join()
we should go for yield() sleep()

MARUTHI CHARAN TEJ 21


Property yield() join() sleep()

Is it
NO YES YES
overloaded?

Is it final? NO YES NO

Is it throws? NO YES YES

sleep(long ms)-
>native & sleep (long
Is it native? YES NO
ms, int ns)-> non
native

Is it static? YES NO YES

12) Explain the main thread under Thread class execution


The main thread is created automatically when our program is started. To control it we must
obtain a reference to it. This can be done by calling the method currentThread( ) which is
present in Thread class. This method returns a reference to the thread on which it is called.
13) What is a daemon thread?
The daemon threads are the low priority threads that provide the background support and
services to the user threads. Daemon thread gets automatically terminated by the JVM if
the program remains with the daemon thread only, and all other user threads are
ended/died. There are two methods for daemon thread available in the Thread class:
• public void setDaemon(boolean status): It used to mark the thread daemon thread
or a user thread.
• public boolean isDaemon(): It checks the thread is daemon or not.
14) Is it possible to start a thread twice?
No, it is not possible to start a thread twice in Java. It is because once a thread starts
executing its run() method, it goes into a running state and it cannot be stopped or
restarted. If you try to start a thread twice, it will throw an IllegalThreadStateException
exception.

MARUTHI CHARAN TEJ 22


15) Can we call the run() method instead of start()?
Yes, calling run() method directly is valid, but it will not work as a thread instead it will work
as a normal object. There will not be context-switching between the threads. When we call
the start() method, it internally calls the run() method, which creates a new stack for a
thread while directly calling the run() will not create a new stack.
16) Can we make the user thread as daemon thread if the thread is started

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

17) When should we interrupt a thread?


You can interrupt a thread to tell it to finish execution as soon as possible. This can include
abandoning current tasks if possible.
In Java, you can use the interrupt() method to interrupt a thread. This method is used when
a thread is in a sleeping or waiting state. When you use the interrupt() method, the thread
execution is interrupted by throwing an InterruptedException.
You can also use the sleep() method to pause the execution of a thread. The sleep() method
takes a specified number of milliseconds and nanoseconds. The allowed nanosecond values
are between 0 and 999999.
18) What are the ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by
unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait()
method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

MARUTHI CHARAN TEJ 23


19) How does multi-threading take place on a computer with a single CPU?
In a multithreaded process on a single processor, the processor can switch execution
resources between threads, resulting in concurrent execution. Concurrency indicates that
more than one thread is making progress, but the threads are not actually running
simultaneously.
20) What are the different types of Thread Priorities in Java? And what is the default
priority of a thread assigned by JVM?
The Thread class defines these priority types as constants MIN_PRIORITY, NORM_PRIORITY,
and MAX_PRIORITY, with values 1, 5, and 10, respectively. NORM_PRIORITY is the default
priority for a new Thread.
21) What do you understand by inter-thread communication?
Inter-thread communication is a mechanism that allows synchronized threads to
communicate with each other. In Java, inter-thread communication is also known as
cooperation.
How it works
• A thread is paused while running in its critical section.
• Another thread is allowed to enter (or lock) in the same critical section to be
executed.
Why it's needed
• To perform multiple actions at the same time. For example, online video players and
audio players.
• To share access to an object's data member.
How to implement inter-thread communication in Java
• Use the wait() and notify() methods.
• Use the higher-level constructs of the java.util.

22)What is the synchronization

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

MARUTHI CHARAN TEJ 24


allows only one thread to be executed at a time. Synchronization can be achieved in three
ways:
• by the synchronized method
• by synchronized block
• by static synchronization

Syntax for synchronized block


1. synchronized(object reference expression)
2. {
3. //code block
4. }

23)What is the purpose of the Synchronized block?


A synchronized block in Java prevents multiple threads from executing a portion of code in a
method at the same time. For example, if there are 100 lines of code and only 10 lines need
to be synchronized, a synchronized block can be used.
The Synchronized block can be used to perform synchronization on any specific resource of
the method. Only one thread at a time can execute on a particular resource, and all other
threads which attempt to enter the synchronized block are blocked.
➢ Synchronized block is used to lock an object for any shared resource.
➢ The scope of the synchronized block is limited to the block on which, it is applied. Its
scope is smaller than a method.
24)Can Java object be locked down for exclusive use by a given thread?
Yes, Java objects can be locked down for exclusive use by a given thread. This is done using
the synchronized keyword. When a thread acquires a lock on an object, no other thread
can acquire a lock on the same object until the first thread releases it. This ensures that only
one thread can access the object's data at a time, preventing data corruption.
25) What is static synchronization?
If you make any static method as synchronized, the lock will be on the class not on the
object. If we use the synchronized keyword before a method so it will lock the object (one
thread can access an object at a time) but if we use static synchronized so it will lock a class
(one thread can access a class at a time).

MARUTHI CHARAN TEJ 25


26) What is the difference between notify() and notifyAll()?
In Java, notify() wakes up a single thread, while notifyAll() wakes up all threads.
notify():
• Wakes up any thread in the wait set
• Selects a random thread from the object's wait set and puts it in the BLOCKED state
• The rest of the threads in the wait set remain in the WAITING state
notifyAll():
• Wakes up all threads in the waiting set
• Moves all the threads from the object's wait set to the BLOCKED state
➢ notify() and notifyAll() are key parts of the producer-consumer design pattern, which
is one of the most useful multithreading patterns for Java developers.
➢ notify() is used in multithreading to send a notification to only one thread among the
multiple waiting threads. notifyAll() sends the notification to all waiting threads.
➢ notifyAll() is generally used. If you are not sure which to use, you can use notifyAll()
27)What is the deadlock?
Deadlock is a situation in which every thread is waiting for a resource which is held by some
other waiting thread. In this situation, Neither of the thread executes nor it gets the chance
to be executed. Instead, there exists a universal waiting state among all the threads.
Deadlock is a very complicated situation which can break our code at runtime.
For example, if P1 requests a resource R2, which is held by P2, P1 will wait indefinitely
because P2 can't release resource 2 until it gets R3, which P3 holds.
28) How to detect a deadlock condition? How can it be avoided?
We can detect the deadlock condition by running the code on cmd and collecting the Thread
Dump, and if any deadlock is present in the code, then a message will appear on cmd.
Ways to avoid the deadlock condition in Java:
➢ Avoid Nested lock: Nested lock is the common reason for deadlock as deadlock occurs
when we provide locks to various threads so we should give one lock to only one thread
at some particular time.
➢ Avoid unnecessary locks: we must avoid the locks which are not required.
➢ Using thread join: Thread join helps to wait for a thread until another thread doesn't
finish its execution so we can avoid deadlock by maximum use of join method.
29) What is Thread Scheduler in java?
In Java, when we create the threads, they are supervised with the help of a Thread
Scheduler, which is the part of JVM. Thread scheduler is only responsible for deciding which

MARUTHI CHARAN TEJ 26


thread should be executed. Thread scheduler uses two mechanisms for scheduling the
threads: Preemptive and Time Slicing.
Java thread scheduler also works for deciding the following for a thread:
➢ It selects the priority of the thread.
➢ It determines the waiting time for a thread
➢ It checks the Nature of thread
30) Does each thread have its stack in multithreaded programming
➢ Yes, in multithreaded programming, each thread has its own stack. The stack is a
region of memory that is used to store local variables, function call parameters, and
return values.
➢ Each thread has its own stack so that they can be independent of each other. This
means that one thread can't access the local variables of another thread.
➢ It also means that when one thread is interrupted and another thread is started, the
two threads can have different values on the stack.
40) How is the safety of a thread achieved?
If a method or class object can be used by multiple threads at a time without any race
condition, then the class is thread-safe. Thread safety is used to make a program safe to use
in multithreaded programming. It can be achieved by the following ways:
➢ Synchronization
➢ Using Volatile keyword
➢ Using a lock based mechanism
➢ Use of atomic wrapper classes
41) What is the purpose of wait() method in Java?
The wait() method is provided by the Object class in Java. This method is used for inter-
thread communication in Java. The java.lang.Object.wait() is used to pause the current
thread, and wait until another thread does not call the notify() or notifyAll() method. Its
syntax is given below.
• public final void wait()
42)Why must wait() method be called from the synchronized block?
We must call the wait method otherwise it will throw java.lang.IllegalMonitorStateException
exception. Moreover, we need wait() method for inter-thread communication with notify()
and notifyAll(). Therefore It must be present in the synchronized block for the proper and
correct communication.

MARUTHI CHARAN TEJ 27


43)What is race-condition?
A Race condition is a problem which occurs in the multithreaded programming when
various threads execute simultaneously accessing a shared resource at the same time. The
proper use of synchronization can avoid the Race condition.
For example, if a system attempts to perform two or more operations at the same time, but
the operations must be done in a specific order, that's a race condition.
44)What is the volatile keyword in java?
Volatile keyword is used in multithreaded programming to achieve the thread safety, as a
change in one volatile variable is visible to all other threads so one variable can be used by
one thread at a time.

45)What do you understand by thread pool?


Java Thread pool represents a group of worker threads, which are waiting for the task to be
allocated.
➢ Threads in the thread pool are supervised by the service provider which pulls one
thread from the pool and assign a job to it.
➢ After completion of the given task, thread again came to the thread pool.
➢ The size of the thread pool depends on the total number of threads kept at reserve for
execution.

The advantages of the thread pool are :


➢ Using a thread pool, performance can be enhanced.
➢ Using a thread pool, better system stability can occur.

MARUTHI CHARAN TEJ 28

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy