Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jun 3, 2024
Difficulty: Easy

Top Java Multithreading Interview Questions (2024)

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

This article lists some of the most common Java multithreading interview questions. These questions can be a way to revise for experienced programmers or a primer for novice programmers to get a handle on Java multithreading interview questions.

Let's begin our journey through the most commonly asked Java multithreading interview questions!

What is Multithreading in Java? Why is it important?

Multithreading in Java is a programming concept that refers to small tasks running simultaneously. Let's take an example of multithreading as our computer or mobile phones, which allows us to run various tasks at once. Its main purpose is to enable multiple threads to run simultaneously, maximizing CPU usage and improving program execution speed. This Java feature allows a program to be divided into multiple threads for faster and easier execution.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Multithreading Interview Questions in Java for Freshers

1.What is a thread in Java?

Threads are referred to as the smallest parts of a process that simply let a program execute efficiently with other parts or threads of the process at the same time. They share a common address space and are independent of each other. In Java, there are two ways of creating threads:

  1. Via Thread class
  2. Via Runnable interface

2. What are the two ways of implementing threads in Java?

The two ways of implementing threads in Java are as follows:

  1. Via Thread class
  • Java

Java

class SampleMultithreading extends Thread {
public void run() {
System.out.println("My thread is currently running.");
}

public static void main(String args[]) {
SampleMultithreading obj = new SampleMultithreading();
obj.start();
}
}


Output: 

My thread is currently running.


2. Via Runnable Interface

  • Java

Java

class SampleMultithreading implements Runnable {
public void run() {
System.out.println("My thread is currently running.");
}

public static void main(String args[]) {
SampleMultithreading obj = new SampleMultithreading();
Thread tobj = new Thread(obj);
tobj.start();
}
}


Output:

 My thread is currently running.

3. What is multitasking in an operating system?

Multitasking is a feature in an operating system that divides system resources among tasks/processes and switches between the tasks/processes while they are executing over and over again. This gives the perception of 2 or more tasks running concurrently. Multitasking is of two types:

→ Process-based multitasking

→ Thread-based multitasking

4.  What are the benefits of using Multithreading?

Multithreading possesses various benefits described below:

  1. It increases the use of CPU resources.
  2. Does not get blocked easily if some parts of it are blocked
  3. It allows the programs to utilize maximum CPU time
  4. Improves the responsiveness of the program.
  5. It allows parallelism.

5. What is a thread lifecycle?

A thread at any instant of time can be found in any one of the following states:

  1. New
  2. Runnable
  3. Blocked
  4. Waiting
  5. Timed waiting
  6. Terminated

6. What is the difference between a thread and a process?

A program in execution is called a process, while the smallest independent units in a process are called a thread.

Thread vs Process

7. What is the task of the main thread?

The main Thread is a thread contained in every program created by the JVM at the start of the program when the main() function is invoked with the main Thread as depicted from the output perceived from pseudo-code illustration.

System.out.println("coding ninjas");
Output: coding ninjas
System.out.println(Thread.getname().currentthread()); 
Output: main

8. What are the different types of threads in Java?

There are two types of threads in Java as follows:

  1. User Thread(Non-daemon thread)
  2. Daemon Thread
User Thread vs Daemon Thread

9. What is the start() and run() method of Thread class?

Start(): The start() method is used to start or begin the execution of a newly created thread. When the start() method is called, a new thread is created, and this newly created Thread executes the task that is kept in the run() method. One can call the start() method only once.

run():  The run() method is used to start or begin the execution of the same Thread. When the run() method is called, no new thread is created, as in the case of the start() method. This method is executed by the current Thread. One can call the run() method multiple times. 

10. How to set the name of the thread?

A method named as setName() is there which is used to change or set the names of the threads.

thread_class_object.setName("Name_thread_here");

11. What do you mean by garbage collection?

Garbage collection is a process of managing memory automatically. A garbage collector finds objects that are no longer required by the program and then deletes or removes these unused objects to free up memory space. It uses several GC algorithms. One popular name of the algorithm is  Mark and Sweep.

12. What is thread Starvation?

When low-priority threads do not get CPU for their execution because high-priority threads occupy the CPU for long periods of time, this phenomenon is called thread starvation. This makes the Thread unable to progress.

13. What is thread priority?

In Java, every Thread has a priority which is represented by the numbers from 1 to 10. The default priority is set to 5, the minimum priority is set to one, and the maximum priority is set to 10. Here, three constants are defined as NORM_PRIORITY, MIN_PRIORITY, and MAX_PRIORITY.

14. What is context switching

Context Switching is referred to as switching the CPU from one Thread or process to another one. In context switching, the state of the Thread is stored so that the next time the execution of the Thread is required, it can be resumed from the same point.

15. What do you mean by inter-thread communication?

It is a mechanism using which multiple threads can communicate with each other. It is especially used to avoid thread polling in Java and can be obtained using wait(), notify(), and notifyAll() methods.

16. What do you mean by finalize() method?

The finalize() method in Java was defined in the Object class before Java version 9. It was supposed to be used for performing cleanup operations on an object before it was garbage collected. After the release of Java 9, this method has been deprecated and it is no longer recommended for managing memory.

Multithreading Interview Questions in Java for Experienced

17. What is the purpose of the finalize() method?

The finalize method in Java is used for performing cleanup operations on objects about to be garbage collected by the JVM. When an object becomes eligible for garbage collection, the JVM checks for a finalize() method and calls it before cleaning the memory. This method can be overridden to define custom cleanup logic. Let's look at the basic syntax of this overriding this method.

class MyClass {
   // Constructor and other methods
   
   // Custom finalize() method for cleanup
   protected void finalize() {
       // Perform resource cleanup here
   }
}

18. What is a semaphore?

Semaphore is regarded as a thread synchronization system that is usually required to control and manage the access to the shared resource using counters. The semaphore class is defined within the package java.util.concurrent and can be used to send signals between threads to avoid missed signals or to guard critical sections.

19. How to make a user thread to daemon thread?

There are two methods in the thread class that is used to make a user thread into a daemon thread. First, the setDaemon() method converts the user thread to the daemon thread and vice-versa. After this, the isDaemon() method is used, which returns a boolean true if the Thread is daemon. Else returns false if it is a non-daemon thread. 

20. Can you start a thread twice?

No, it's not at all possible to restart a thread once a thread gets started and completes its execution. Thread only runs once, and if you try to run it for a second time, then it will throw a runtime exception, i.e., Java. lang.IllegalThreadStateException. 

21. What are the tasks of the start() method?

The main task of the start() method is to register the Thread with the thread scheduler, so one can tell what child thread should perform, when, and how it will be scheduled that is handled by the thread scheduler. The second task is to call the corresponding run() method.

22. Explain the difference between class lock and object lock?

A class lock is present within the class and prevents simultaneous access to a concurrent static method or block. While object lock is related to the instance of a class that allows simultaneous access to concurrent methods or blocks in different objects.

23. Explain the difference between User thread and Daemon thread?

A user thread is also known as high priority thread. The Java virtual machine completes all the user threads before terminating. While the daemon thread is also known as low priority thread, and they are mainly used as background tasks and provide services to the user thread. 

24. What are the wait() and sleep() methods?

The wait() and sleep() methods are used to stop any running thread and convert them into a non-runnable state. The wait method is mostly used for thread sync, and the sleep() method is used to pause the running threads.

25. Explain the  difference between notify() and notifyAll()?

The notify() method is used to alert only one waiting thread among many waiting threads, while the notifyAll() method is used to send notifications to all the waiting threads. notify() method uses less memory and CPU in comparison to the notifyAll() method.

26. What do you mean by thread pool?

A thread pool can be considered a collection of all the threads that are ready to perform the tasks. It also increases the reusability of the threads as it does not create and destroy the threads each time.

27. Can two threads execute two methods (static and non-static concurrently)?

Yes, two threads can run two different methods (one static and one non-static) of the same class. However, it is important to note that unexpected behavior can occur because the locking mechanism will lock two different things: the object and the class itself, which means both methods will execute simultaneously, and a shared state can be mutated.

28. What is meant by volatile variables in Java?

In Java, the volatile keyword is used to declare a variable as volatile, which means changes made to it by one thread will be immediately visible to other threads. You can use this keyword to define simple flags or status indicators frequently checked by many threads.

29. What’s the purpose of the join() method?

The join() method in Java is provided by the Thread class and used for thread synchronization and coordination. This method allows you to make a thread wait for the completion of another thread. 

For example, there are two threads, A and B. If thread A calls the join() method on thread B, thread A will pause its execution and wait for thread B to complete.

30. How do synchronized methods and synchronized blocks differ, and which one is the preferred choice?

Synchronized methods and blocks in Java are used to achieve thread synchronization and prevent multiple threads from concurrently accessing critical code sections. The choice between synchronized methods and synchronized blocks depends on your specific requirements:

  • Synchronized Methods: Use synchronized methods when you want to synchronize the entire method and there's no need to synchronize different parts of the method separately.
     
  • Synchronized Blocks: Use synchronized blocks when you need more control over synchronization, and you want to synchronize specific sections of code. Synchronized blocks are more flexible and allow for finer-grained synchronization.

31. What is meant by deadlock and how it can occur?

A deadlock is a situation in which two or more threads are blocked for an infinite time, and they all wait for each other to release their resources. Deadlock can occur due to mutual exclusion, holding and waiting of threads or when a circular chain of two or more threads exists.

Frequently Asked Questions

Is it possible to call the run() method directly to start a new thread?

No, it's not possible at all. You need to call the start method to create a new thread otherwise it will execute in the current thread.

Can we Overload run() method?

Yes, it is possible to overload run() by passing parameters to it and also keeping a check over to comment down @override from the run() method. 

Why is multithreading required?

Multithreading is required in order to enhance the performance and to improve the responsiveness of the process.

Conclusion

In conclusion, multithreading is a crucial aspect of Java and modern software development, enhancing program efficiency and reducing resource usage. This article covered key multithreading interview questions and answers to help you succeed in your interviews.

Recommended Readings:

Refer to our guided paths on Coding Ninjas Code360 to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must have a look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Topics covered
1.
Introduction
2.
What is Multithreading in Java? Why is it important?
3.
Multithreading Interview Questions in Java for Freshers
3.1.
1.What is a thread in Java?
3.2.
2. What are the two ways of implementing threads in Java?
3.3.
Java
3.4.
Java
3.5.
3. What is multitasking in an operating system?
3.6.
4.  What are the benefits of using Multithreading?
3.7.
5. What is a thread lifecycle?
3.8.
6. What is the difference between a thread and a process?
3.9.
7. What is the task of the main thread?
3.10.
8. What are the different types of threads in Java?
3.11.
9. What is the start() and run() method of Thread class?
3.12.
10. How to set the name of the thread?
3.13.
11. What do you mean by garbage collection?
3.14.
12. What is thread Starvation?
3.15.
13. What is thread priority?
3.16.
14. What is context switching
3.17.
15. What do you mean by inter-thread communication?
3.18.
16. What do you mean by finalize() method?
4.
Multithreading Interview Questions in Java for Experienced
4.1.
17. What is the purpose of the finalize() method?
4.2.
18. What is a semaphore?
4.3.
19. How to make a user thread to daemon thread?
4.4.
20. Can you start a thread twice?
4.5.
21. What are the tasks of the start() method?
4.6.
22. Explain the difference between class lock and object lock?
4.7.
23. Explain the difference between User thread and Daemon thread?
4.8.
24. What are the wait() and sleep() methods?
4.9.
25. Explain the  difference between notify() and notifyAll()?
4.10.
26. What do you mean by thread pool?
4.11.
27. Can two threads execute two methods (static and non-static concurrently)?
4.12.
28. What is meant by volatile variables in Java?
4.13.
29. What’s the purpose of the join() method?
4.14.
30. How do synchronized methods and synchronized blocks differ, and which one is the preferred choice?
4.15.
31. What is meant by deadlock and how it can occur?
5.
Frequently Asked Questions
5.1.
Is it possible to call the run() method directly to start a new thread?
5.2.
Can we Overload run() method?
5.3.
Why is multithreading required?
6.
Conclusion