Top 100+ Java Multi-Threading Interview Questions with Answers For 0 to 5 Years of Experience

In the previous article, I wrote about Top 51+ Java Map Interview Questions Answers For 0 to 5 Years experience. In this article, I am going to share Top 100+ Java Multi-Threading Interview Questions with Answers frequently asked on Interview. You can expect many questions from this topic in the interview.

Q1. What is multithreading in Java?
Ans:
Multithreading in java is a process of executing multiple threads simultaneously. Multithreading is mostly used in games, animation, etc.

Q2. What is a thread?
Ans:
Thread is a flow of execution of the program. For every thread, there is some job or some task. It is lightweight subprocess, the smallest unit of processing. Thread is independent. It uses a shared memory area. Each independent part of the program is a thread. Thread increases the performance of the system. It belongs to java.lang.package.

Q3. How the thread is beneficial?
Ans:
Consider, One thread takes 5 minutes to complete a certain task, then 5 threads could complete that task in 1 minute as threads run parallelly. So it increases the performance and uses to make the task faster

Q4. What are the Advantages of Multithreading in java?
Ans:
The advantages of the multithreading in java are as follows:

  • Threads are independent and you can perform multiple operations at the same time.
  • It saves time. You can perform many operations together.
  •  if an exception occurs in a single thread then also it doesn’t affect other threads as threads are independent.

Q5. What is multitasking in multithreading?
Ans:
Multiple tasks are being done at the same time is called multitasking. We use multitasking to utilize the CPU.

Q6 What are the types of multitasking?
Ans:
Multitasking is of mainly two types:

  • Thread-base Multitasking
  • Process-base Multitasking

Q7. What do you understand by Thread-base Multitasking?
Ans:
In case of thread-base Multitasking, resources required will be shared with the help of scheduling algorithms. As these threads are the smallest unit of the process, which is having it own path of execution.

Q8. What do you understand by Process-based Multitasking?
Ans: Processes may or may not be implemented in one or different programming languages. In the case of process-based resources required or available will not be shared.
In java, SUN has implemented or provided its own API to work with threads. Following are the API to work with threads. Following are the API given by SUN Microsystems.

  • Java.lang.Thread class
  • Java.lang.Runnable Interface
  • Java.lang.ThreadGroup class

Q9. Why Java provides Thread class?
Ans:
Java provides a Thread class to achieve thread programming.

Q10 Name the interface and a class which Thread class extends or implements?
Ans:
Thread class extends Object class and implements the Runnable interface.

Q12. What is the start () method in multithreading?
Ans:
This method is used to start the execution of the thread. Although it is not compulsory that thread will start execution by calling the start method of it. It totally depends on the thread scheduler.

Q13. What is the run() method?
Ans:
It is used to do an action for a thread. Inside the run method, we write the task of the thread which we want the thread to perform.

Q14. How multiple threads are managed by JVM?
Ans:
In Java, multiple threads are being managed by a special life cycle mechanism.

Q15. Explain the process. When JVM starts?
Ans:
Whenever JVM starts, it creates one thread group with the name of main, under that thread group it creates one more thread named as main. continuation of this is in the next question’s answer

Q16. What are the responsibilities of the main thread?
Ans:
Main thread is responsible for the following work:

  • The main thread will create the default object of type String.
  • With the name of the reflection mechanism, it takes the name of the class with which you are trying to run the program.
  • With the help of the class name, it calls the main method of the program by passing string object as a parameter, immediately after calling the main method or after completing the task assigned to the main thread. JVM will destroy the main thread.

Q17. Can we change the name of the main thread?
Ans:
Yes, we can change the name of the main thread by using the setName() method.

Q.18 Can I change the name of the main thread group?
Ans:
No, we can’t change the name of the main thread group.

Q19. What do you understand by a user-defined thread and also tell the way to create the user-defined thread?
Ans: User-defined or custom thread are created by the user by writing your own implementation.

A user-defined thread can be developed by using the two different way:

  • By extending the Thread class
  • By implementing the Runnable interface.

Q20 What are the steps to create a custom thread by extending thread class?
Ans:
These are the following steps to create a custom thread by extending the thread class.

  • Write your thread class by extending thread class
  • invoke the thread class constructor by using the super keyword.
  • Start each thread by writing the start method.
  • Override the run() method inside the class.

Q21 Is it mandatory to override the run() method while creating a custom thread by extending thread class?
Ans:
No, it is not mandatory to override the run() method because the implementation of the run method is available inside the thread class.

Q22. Write a program to create a custom thread by extending thread class?
Ans:

class c extends Thread
{
public  XadminThread ()
{
super();
start();
}
XadminThread(String tname)
{
super(tname);
start();
}
XadminThread(String tname, ThreadGroup tg)
{
super(tg,tname);
start();
}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println()Thread.currentThread().getName());

try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printstackTrace();
}
}
}
}
 class Xadmin
{
Static 
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[])
{
ThreadGroup tg = new ThreadGroup(“xadmin”)
XadminThread th1 = new XadminThread();
XadminThread th2 = new XadminThread(“xadmin”);
XadminThread th3 = new XadminThread(“xadmin”, tg);
for(int i=0; i<5; i++)
{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printstackTrace();
}
}
}

Q23. What are the steps to create a custom thread by a runnable interface?
Ans:
These are following steps to create a custom thread by Runnable interface.

  • Write your thread class by implementing the runnable interface.
  • Define some instance variable if required.
  • Invoke the thread class constructor.
  • Override the run method here, it is mandatory to override the run method.

Q24. Write a java program to create a custom thread by a runnable interface
Ans:

 

Class XadminThread implements Runnable
{
public  XadminThread()
{
Thread t1 = new Thread(this);
t1.start();
}
public  XadminThread(string tname)
{
Thread t2= new Thread(this, tname);
t2.start();
}
public  XadminThread(String tname, ThreadGroup tg)
{
Thread t3 = new Thread(tg, this,tname)
t3.start();
}
public void run()
{
for(int i=0; i<5;i++)
{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printstatckTrace();
}
}
}
}
public  class Xadmin
{
public static void main(String args[])
{
ThreadGroup tg1= new ThreadGroup(“xadmin”);
XadminThread th1 = new  XadminThread();
XadminThread th2 = new  XadminThread(“Xadmin1”);
XadminThread th3 = new  XadminThread(“xadmin2”,tg1);

for(int i=0; i<5; i++)
{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
}
e.printStackTrace();
}
}
}
}

Q25. What do know about thread priority?
Ans:
Each thread has a priority. Priority is represented by a number between 1 to 10. Number 1 represented as a minimum priority and number 10 represent as maximum priority.

Q26 What is the method by which we can set the priority or get the priority of the thread?
Ans:
By using the following two methods, we can set the priority and can get the priority

  • public final void setPriority(int);
  • public final int getPriority();

Q27. What are the constraints defined in the java.lang.thread class for the priority?
Ans:
There are mainly three constraints define in java.lang.Thread class

  • public static final int MIN_PRIORITY; – 1
  • public static final int NORM_PRIORITY; – 5
  • public static final int MAX_PRIORITY; – 10

Q28. What is the life cycle stages of a thread?
Ans:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies.

Q29. Explain the whole life cycle of a thread?
Ans:
The following diagram shows the complete life cycle of a thread.

Start –> Ready to run state

  • When you are starting any thread by writing the start() method then that thread will get started to move toward Ready to run-state.
  • Now, this thread will wait in ready to run-state for its own turn.
  • According to the CPU scheduler algorithms, whichever thread matches the CPU algorithms that thread will be scheduled for running state.

Ready to run state –> Running state

  • Just by starting the thread, any thread will not be processed.
  • When CPU scheduler selects any thread from running state then only that thread will be processed.
  • At a time, only one thread can be processed in the running state.

Running state –> sleep

  • when a thread is processing and if a running thread is asked to sleep by calling sleep method then that running thread will move to sleep state for the specified amount of time
  • After completing the sleep time, the thread will move to the ready to run state and again it will wait for its turn to get selected by CPU scheduler algorithm.
  • When a thread is there in a sleep state. The thread can’t be notified by notifyAll() or notify() method.

Running state to –>wait state

  • when a thread is in running state and if we are calling with wait() method with parameter then that thread will move to wait-state for a specified amount of time.
  • After completing the wait time the thread will move automatically to the ready to run-state.
  • If you are calling wait() method without passing parameter then that thread will move to the wait state for an unspecified amount of the time till the time thread is being not notified by notifyAll() and notify() method then thread will be there in the waiting state only.

Note:
While waiting for the thread we can send the thread in Ready to run by notify() or notifyAll() method but not with sleep() method, in sleep state thread will complete the sleep state then only it will move to ready to run a state.

Running state to –> Blocked state

  • when a thread is there in the running state and requesting for some specified resource and that resource is not available then that thread will move to the blocked state. It will move to ready to run state from the blocked state only when the corresponding resource is available.
  • If a thread is running and we called stop() or suspend method then thread will move to the dead state.

Note: Even a thread is completed it assigned task then also it will move to dead state. Once the thread is moved to dead state then that thread can’t be restarted or it can’t be a move to ready to run-state.

Q30. when exactly run() method will get called?
Ans:
 whenever a thread gets the CPU time at that time the run() method will be called.

Q31 Can I ask any specific thread to sleep.
Ans:
 No, we can,t because we don’t know which thread is running.

Q32 Can I ask any specified thread to wait?
Ans:
No, we can’t ask any specified thread to wait.

Q33. What is notify() and notifyAll() method?
Ans:
Notify(): whenever we are calling notify method then the thread which is there in the waiting for a longer time will move first to ready to run-state.

NotifyAll(): when notifyAll() method is called all the thread which are there in the waiting state will move to ready to run state by maintaining first go first order.

Q34 What is Dead Lock?
Ans:
Consider. there are two thread t1 and t2 and if using resources R1 and R2 respectively. If t1 is requesting for resource R2 and t2 is requesting for resource R1 but thread t1 will release resource R1 only after getting resource R2 and t2 will release resource R2 only after getting resource R1. This situation creates Dead Lock.

Q35 What is Inline Thread?
Ans:
Thread which is just processed one time.

Q36 Write a java program for inline thread
Ans:

Class Hello
{
void m1()
{
System.out.println(“m1 method inside m1”);
new Thread()
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(500);
}
catch(Exception e)
{
e.printstackTrace();
}
}
}
}.start();
}
}
public class Xadmin
{
Hello h1 = new Hello();
h1.m1();
}

Q37. How many ways to stop or prevent the execution of thread?
Ans:
We can stop the thread execution by using these three methods

  • yields()
  • join()
  • sleep()

Q38. What is yields() method?
Ans:
we call this yield() method by writing Thread.yield(). This method causes to pauses current executing thread to give the chance for waiting thread of same priority. If there is no waiting thread or all waiting thread have low priority than the same thread can continue its execution.

T1–>7

T2–> 7

T3–> 7

T4–> 7

consider, currently, T4 thread is executing and if Thread.yield() is called then thread T4 execution will get paused and it will give chance to other thread of same priority. T4 will go to wait-state. If yield() method is called then thread goes to Running state to Ready/Run state.

Q39. A thread which is the yield, when it will get a chance once again?
Ans:
It depends on CPU scheduler.

Q40. What is Join() method of thread class?
Ans:
If a thread wants to wait until completing some other thread then we should go for the join() method. if thread t1 wants to waits till thread t2 completes it task. Then t1 has to call join method on t2 like t2.join(). If t1 executes t2.join() then immediately t1 will enter into wait-state until t2 completes its task. Once the t2 completes its task then t1 can continue it execution.

Q41.What is the prototype of the join() method?
Ans:

  • public final void join(); this throws an interrupted exception
  • public final void join(long ms); This throws an interrupted exception
  • public final void join(long ms, int ns) this throws an interrupted exception.

Q42. What is the sleep method of the Thread class
A
ns: If a thread doesn’t want to perform its work for any amount of time and thread wants to wait then sleep() method should be called on it.

Q43. What are the signatures of sleep() method?
Ans:

  • public static native void sleep(long ms)
  • public static void sleep(long ms, int ns); throws Interrupted exception

Q44 Write a java program by using sleep method?
Ans:

class Xadmin
{
public static void main(Static args[]) throws Interrupted exception
{
for(int i=0; i<=10;i++)
{
System.out.println(“value of i”+i);
Thread.sleep(5000);
}
}
}

Q45 Can a thread interrupt another thread?
A
ns: Yes, Thread class contain one method called interrupt() method. The signature of interrupt method: public void interrupt();
Thread can interrupt a sleeping thread or a waiting for a thread by using the interrupt method of thread class.

Q46 What will happen If interrupt() method is invoked by any thread and any thread is not in wait state or in sleep state?
Ans:

If interrupt() method is invoked by any thread and if any thread is not waiting nor in the sleeping state then interrupt method will not get wasted. It will wait for the thread to enter in sleep or in a wait state.

If Interrupt() method is invoked and if target thread never entered into sleep or wait-state in it lifetime then there is no impact of interrupt call method. This is the only case where interrupt method call will be wasted.

Q47 Difference between yield(), join() and sleep()?
Ans:
Comparison of yield() , join(), and sleep() method

Property yield() join() sleep()
purpose If the thread wants to pause its execution and give chance to other same priority thread to execute then yield() is used It is the thread wants to wait() until completing some other thread then we should go for join() If a thread doesn’t want to perform any operation for a particular amount of time then go for the sleep() method
It is overload No Yes Yes
Is it final No Yes No
IS it throws InterruptedException No Yes Yes
Is it a native method Yes No sleep(long ms) is native

sleep(long ms, int ms) is non-native

Is it a static method yes No Yes

Q48. Is Thread behavior predictable?
Ans: No, Thread behavior not predictable because the execution of Threads depends on CPU scheduler or Thread scheduler may have a different implementation on different platforms like Windows, Unix, etc. Same threading program may produce different output in subsequent executions even
on the same platform.

Q49 What can you say about starting a thread with a run() and start() method?
Ans: When we call or invoke start() method, then JVM creates a new thread, with this newly created thread a run method will be invoked.
In case of calling the run() method, JVM will not create a new thread, but the main thread itself invokes a run() method.

Q50. Can you start a thread twice?
Ans: No, because once the run() method of the thread is invoked after that it will go to dead state. While doing so it will throw a runtime exception.

Q.51 What do you know about race condition in multithreading and what is the way to solve this problem?
Ans.: When more than one thread tries to access the same resource without synchronization causes race condition.

So we can solve race condition by using either the synchronized block or synchronized method.

Q52 What is mutual Exclusion?
Ans: When no two threads can access the same resource at a time, then this phenomenon is also called as mutual exclusion. This can be achieved by using a synchronized block or synchronized method.

Q53. Why wait() method be called from the synchronized block?
Ans: We must call the wait() method from the synchronized block. As it will throw java.lang.illegalMonitorStateException exception.

Q54 Difference between Wait() and sleep() method?
Ans: 1) Wait() method is from Object class whereas the Sleep() method is from Thread class.

2) Wait() method release the lock whereas Sleep() method doesn’t release the lock method.

Q55 What is currentThread() method do?
Ans: This method returns a reference to the currently executing thread object.

Q56. What is the use of the getPriority() method?
Ans: This method returns the priority of the thread.

Q57 What is the use of the setPriority() method?
Ans: It changes the priority of the thread.

Q58. What is Void suspend() method do?
Ans: It suspends the thread.

Q59. What is void resumes() method do?
Ans: This method is used to resume the suspended thread.

Q60. What is the stop() method?
Ans: This is used to stop the thread.

Q61. What is Boolean isDaemon() method?
Ans: This method is used to test the thread as daemon thread.

Q62. What is the Void setDaemon() method?
Ans: It makes the thread as daemon or user thread.

Q63. What is the Void destroy() method?
Ans: This method is used to destroy the thread group and all of its subgroup.

Q64. What is Boolean isinterrupted() method do?
Ans: This method is used to check whether the thread is interrupted or not.

Q65. What is Void notify() method do?
Ans: This method is used to give the notification for only one thread which is waiting for a particular object.

Q66. What is Void notifyAll() method do?
Ans: It is used to give the notification to all the waiting threads of a particular object.

Q67 What is shutdown hook?
Ans: This method is invoked before the JVM closes normally or abruptly. So it is used for the clean up the resources.

Q68. When an interrupt method is used?
Ans: Interrupt method is called or used when we want to awake the sleeping thread or waiting thread.

Q69 Does every thread maintain a separate stack area?
Ans: Yes, in multithreaded programming every thread maintains its own or separate stack area in memory due to which every thread is independent of each other.

Q70. How to create a daemon thread?
Ans: We can create a demon thread by calling setDemon(true).

Q71. What is the use of volatile keyword?
Ans: If a variable is made volatile, then all the threads will read its value directly from the memory and it doesn’t cache it. It updates the variables consistently.
Q72. Can you make the method or block volatile?
Ans: No, not possible Only volatile is used on variables.

Q73. What is synchronization?
Ans: It the capability to control the access of multiple threads to any shared resources.

Q74. What is the advantage of Thread synchronization?
Ans: 1) Thread synchronization avoids a consistency problem.

2) Thread synchronization avoids thread interference.

Q75. Which is the best to use synchronization block or synchronization method?
Ans: Synchronized block is the best to use because it doesn’t lock the object while the synchronized method locks the object.

Q76. What is the InheritableThreadLocal class?
Ans: InheritableThreadLocal is a child class of ThreadLocal class and all methods present in ThreadLocal by default available to inheritable thread-local.

Q77. What are the constructors of the InheritableThreadLocal class?
Ans: InheritableThreadLocal t1= new InheritableThreadLocal();

Q78. What is Thread Group?
Ans: Thread group can contain a sub-thread group. Threadgroup->(Threads + sub-thread group). Thread group is used to do a common operation. Every thread in java belongs to some group. It is present in java.lang.package. Thread group is a direct subclass of an object class.

Q79. What is the parent class of the thread group?
Ans: Every thread group in java is a child of the system group.

Q80. What are the system-level threads present in the system group?
Ans: System group contains several system-level threads like

1) Finalizer

2) Reference Handler

3) Signal Dispatcher

4) Attach Listener

Q81. What are the constructors of the thread group?
Ans: The constructors are:

1) ThreadGroup g= new ThreadGroup(String name);

2) ThreadGroup g = new ThreadGroup(ThreadGroup m, String groupName);

Q82. What is String getName() method of ThreadGroup do?
Ans: It will return the name of the Thread group.

Q83. What is int getMaxPriority(int p)?
Ans: This method returns the maximum priority of the thread group.

Q84. What is void setMaxPriority(int p) method of the Thread Group?
Ans: This is used to set the maximum priority of the thread group.

Q85. What is void getParent() method of the Thread Group?
Ans: It will return the parent name of the thread group.

Q86. What is void list() method of the Thread Group?
Ans: It prints information about the thread group to console

Q87. What is int activeCount() method of the Thread Group?
Ans: This method returns the count of active thread present in the thread group.

Q88. What is int activeGroupCount() method of the Thread Group?
Ans: This method return no. Of the active groups present in the current thread group.

Q89. What is enumerate(Thread [] t)?
Ans: This will copy all active thread of this thread group into provided thread array in this case sub-thread group thread will be considered

Q90. What is void destroy() do?
Ans: To destroy thread group and it sub-thread groups.

Q91. What is boolean isDaemon() method do?
Ans: It checks whether the thread group is Daemon or not.

Q92. How to check the thread holds the lock on an object or not?
Ans: By using boolean holdsLock() method. If it returns true then it shows thread holds the lock on the thread.

Q93. What do you understand by ThreadPool?
Ans: ThreadPool is a memory in which thread is waiting for their turn to execute. It is a pool of worker threads.

Q94. What is a transient variable?
Ans: transient variables are variable which cannot be serialized during the serialization process. It is initialized to a default value of the variable during serialization.

Q95. What is an atomic operation?
Ans: Atomic operations are performed in the unit of task without interference from other operation. It avoids data inconsistency.

Q96. What is the lock interface in java API concurrency API?
Ans: Lock interface provides more extensive locking operations than can be obtained using synchronized methods and statements.

Q97. What do you know context-switching in multi-threading?
Ans: It is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. Context Switching is the essential feature for multitasking operating system and support for a multi-threaded environment.

Q98. What is Thread Scheduler and Time Slicing?
Ans: Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads. Once we create and start a thread, it’s execution depends on the implementation of Thread Scheduler. Time Slicing is the process to divide the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the thread waiting for a longer time will get more priority in getting CPU time. Thread scheduling can’t be controlled by java, so it’s always better to control it from the application itself.

Q99. Can you synchronize the constructor?
Ans: No. Not possible.

Q100. How thread communicate with each other?
Ans: Thread communicate with each other through wait(), notify() and notifyAll() method.

That’s all about Multi-Threading interview questions with answers from Core Java Interviews. I have covered almost everything as per my knowledge for both freshers and experienced with 0 to 5 years, so prepare well for the Java interview Questions, I suggest you take a look at more Java Programming Interview Questions with answers on different topics of the core java posted in this xadmin website. Keep Learning!  All the Best!