Posted in

MULTITHREADING INTERVIEW QUESTIONS IN JAVA

1. What is multithreading in Java?

       Multithreading in Java allows multiple threads to run concurrently within a single program. Each thread executes independently, enabling tasks to be processed in parallel, improving performance and responsiveness. Java supports multithreading through the Thread class and Runnable interface. It is especially useful in applications that require handling multiple tasks, such as web servers or background processes. By utilizing multiple CPU cores, multithreading enhances resource usage. Overall, it enables efficient task execution and better overall application performance.

2. What is thread in java?

A thread in Java is a lightweight, independent unit of execution within a program. It allows multiple tasks to run concurrently, enabling parallel processing. Java provides the Thread class and Runnable interface to create and manage threads. Each thread has its own execution path and can perform tasks asynchronously, improving application performance.

3. What is the difference between process and thread?

Feature                      Process                   Thread
DefinitionA process is an independent program in execution with its own memory space.A thread is a smaller unit of a process that executes independently but shares memory space with other threads in the same process.
MemoryEach process has its own memory space.Threads within the same process share memory space.
ExecutionProcesses run independently of each other.Threads within a process run concurrently and share resources.
CommunicationInter-process communication (IPC) is required.Threads can communicate easily within the same process.
CreationCreating a process is slower and more resource-intensive.Creating a thread is faster and less resource-intensive.

4. What is the Thread class and how does it work in Java?

The Thread class in Java is part of the java.lang package and represents a single thread of execution in a program. It provides methods to create, control, and manage threads.

How it works:

  1. Creating a Thread:
    1. You can create a thread by either extending the Thread class or implementing the Runnable interface.
  2. Starting a Thread:
    1. To start the thread, you call the start() method, which internally invokes the run() method in a new thread.
  3. Running the Thread:
    1. The run() method defines the code to be executed by the thread. You override this method to specify the thread’s behavior.
  4. Thread States:
    1. A thread goes through several states like New, Runnable, Blocked, Waiting, and Terminated.

5. How do you create a thread in Java?

you can create a thread in two ways:

1. By Extending the Thread Class:

  • Create a subclass of the Thread class.
  • Override the run() method to define the code that the thread will execute.
  • Create an instance of the subclass and call the start() method to begin execution.

Example :

class MyThread extends Thread {
    public void run() {
        System.out.println(“Thread is running”);
    }
}
public class Test {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();  // Starts the thread
    }
}

2. By Implementing the Runnable Interface:

  • Create a class that implements the Runnable interface.
  • Implement the run() method in that class.
  • Create a Thread object, passing the Runnable instance as an argument, and then start the thread.

Example :

 class MyRunnable implements Runnable {
    public void run() {
        System.out.println(“Thread is running”);
    }
}
public class Test {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();  // Starts the thread
    }
}

6. What are the different thread states in Java?

     A thread can be in the following states:

  1. New: The thread is created but not yet started.
  2. Runnable: The thread is ready to run and can be executed by the CPU.
  3. Blocked: The thread is waiting for a resource currently held by another thread.
  4. Waiting: The thread is waiting indefinitely for another thread to perform a specific action.
  5. Terminated: The thread has completed its execution.

These states represent the lifecycle of a thread from creation to completion.

7. What is thread life cycle?

The thread life cycle in Java refers to the various states a thread undergoes from its creation to its termination. These states are controlled by the JVM and determine the thread’s execution flow. The life cycle consists of the following stages:

  1. New: Thread is created but not started.
  2. Runnable: Thread is ready to run and awaiting CPU time.
  3. Blocked: Thread is waiting for a resource held by another thread.
  4. Waiting: Thread is waiting for another thread to perform a specific action.
  5. Terminated: Thread has completed execution.

The thread moves through these states based on various conditions, controlled by the JVM.

8. What happens when the start() method is called on a thread?

When the start() method is called on a thread, it:

  1. Creates a new thread and transitions it to the Runnable state.
  2. The JVM automatically invokes the run() method of the thread in a new execution context.
  3. The thread begins execution when the scheduler allocates CPU time.

9. What is the difference between sleep() and wait()?

The difference between sleep() and wait() in Java:

  • sleep(): Makes the current thread pause for a specified amount of time (in milliseconds). It does not release any locks or synchronization, and it resumes automatically after the specified time.
  • wait(): Causes the current thread to release any locks and enter the waiting state until another thread calls notify() or notifyAll() on the same object. It is typically used in synchronized blocks or methods.

10. What is the difference between join() and sleep() methods?

  • join(): Makes the calling thread wait until the target thread completes execution. It causes the current thread to enter the Waiting state.
  • sleep(): Pauses the current thread for a specified amount of time, causing it to enter the Timed Waiting state, but it doesn’t affect other threads.

11. What is the Terminated state in the thread lifecycle?

The Terminated state in the thread lifecycle is the final state of a thread.

A thread enters the Terminated (or Dead) state when:

  • Its run() method completes execution normally, or
  • It is abruptly terminated due to an uncaught exception.

Once a thread is terminated, it cannot be restarted.

12. What is the difference between the Runnable state and the Blocked state?

State Runnable Blocked
MeaningThread is ready to run and waiting for CPU time.Thread is waiting to acquire a lock held by another thread.
ExecutionMay be running or waiting to be scheduled by CPU.Cannot run until the lock is released.
CauseEnters after calling start() or being notified.Enters when trying to access a synchronized block/method that’s locked.
StatusEligible for execution.Not eligible for execution until the lock is acquired.

13. Can a thread transition directly from the New state to the Terminated state?

No, a thread cannot transition directly from the New state to the Terminated state in Java.A thread must first be started using the start() method, which moves it to the Runnable state. Only after the run() method finishes (normally or due to an exception) does it enter the Terminated state.If start() is never called, the thread simply stays in the New state and is never executed or terminated.

14. What happens when a thread is in the Blocked state?

    When a thread is in the Blocked state, it is waiting to acquire a lock (monitor) on an object that is currently held by another thread.

Key points:

  • The thread cannot proceed until the lock is released.
  • It usually happens when trying to enter a synchronized block or method that is already in use by another thread.
  • Once the lock becomes available, the thread moves back to the Runnable state and waits for CPU time.

15. How does notify() and notifyAll() affect the thread states?

The notify() and notifyAll() methods in Java are used to wake up threads that are in the Waiting state.

Effects on thread states:

  • notify(): Wakes up one randomly chosen thread that is waiting on the same object’s monitor.
  • notifyAll(): Wakes up all threads waiting on the object’s monitor.

Once notified, the waiting threads move from the Waiting state to the Runnable state, but they still need to re-acquire the lock before continuing execution.

These methods are typically used inside synchronized blocks or methods.

16. What happens if a thread is interrupted while in the sleep() or wait() state?

    If a thread is interrupted while it is in the sleep() or wait() state, it will:

  1. Immediately wake up.
  2. Throw an InterruptedException.
  3. Exit the sleeping or waiting state unless the exception is handled to resume it.

Example:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    System.out.println(“Thread was interrupted during sleep.”);
}
So, the thread stops sleeping or waiting and must handle the interruption using a try-catch block.

17. What is the run() method in Java?

The run() method in Java defines the code that a thread will execute when it starts.

  • It is part of the Runnable interface and also used when extending the Thread class.
  • When you call start(), the JVM internally calls the run() method in a new thread.
  • You must override this method to define the task the thread should perform.

Example:

public void run() {
    System.out.println(“Thread is running…”);
}

18. What is the sleep() method in Java?

   The sleep() method in Java is used to pause the execution of the current thread for a specified amount of time (in milliseconds).

Key points:

  • It is a static method of the Thread class.
  • Syntax: Thread.sleep(timeInMillis);
  • It can throw an InterruptedException, so it must be used inside a try-catch block.
  • During sleep, the thread stays in a Timed Waiting state and resumes automatically after the time expires.

19. What is deadlock in java?

    A deadlock in Java is a situation where two or more threads are blocked forever, each waiting for the other to release a resource.

Key points:

  • It occurs when multiple threads hold locks and each thread is waiting for a lock that another thread holds.
  • Since no thread can proceed, the program becomes stuck.
  • Deadlocks are common in programs with synchronized blocks or methods.

20. Can deadlock be avoided in Java? How?

 Yes, deadlock can be avoided in Java by:

  1. Lock Ordering: Always acquire locks in a consistent order to prevent circular waiting.
  2. Timed Locking: Use tryLock() with a timeout to avoid indefinite waiting.
  3. Lock Hierarchy: Establish and follow a lock hierarchy to prevent circular dependencies.
  4. Minimize Synchronized Blocks: Keep synchronized blocks as short as possible.

These practices help prevent deadlocks by ensuring that threads don’t block each other indefinitely.

21. How can we detect deadlock in Java?

Deadlock in Java can be detected using:

  1. Thread Dump: Analyzing the stack trace of threads to see if they are waiting on each other for resources.
  2. JVM Monitoring Tools: Tools like JVisualVM or JConsole can detect deadlock situations by showing thread states.
  3. Thread.getAllStackTraces(): This method returns stack traces of all threads, helping identify deadlocks.
  4. Custom Deadlock Detection: Implementing logic to check for cycles in thread lock dependencies.

These methods help identify deadlocks in a running Java application.

22. What is the role of Thread.sleep() in deadlock?

The Thread.sleep() method can contribute to deadlock by causing threads to hold onto locks for longer than necessary.

How it affects deadlock:

  • When a thread is sleeping, it may still hold locks that other threads need to proceed.
  • If a thread sleeps while holding a lock, other threads waiting for that lock can become blocked.
  • If multiple threads sleep while holding locks, they can end up in a deadlock situation, where no thread can make progress.

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

   There are two main types of threads:

  1. User Thread:
    1. These are the threads created by the user (programmer) to perform specific tasks.
    1. They are part of the main application and continue executing until they complete or the program terminates.
    1. By default, threads created using the Thread class or implementing Runnable are user threads.
  2. Daemon Thread:
    1. Daemon threads are background threads that provide services to user threads (e.g., garbage collection, housekeeping tasks).
    1. They are automatically terminated when all user threads finish execution.
    1. Daemon threads are created by calling setDaemon(true) on a Thread object before starting the thread.

24. What is Daemon Thread in Java and explain their properties?

   A Daemon Thread in Java is a thread that runs in the background to perform auxiliary tasks, such as garbage collection, and is not crucial for the program’s execution.

Properties of Daemon Threads:

  1. Background Service: It provides background services to user threads.
  2. Termination: Daemon threads automatically terminate when all user threads finish.
  3. Created by setDaemon(true): You can set a thread as a daemon by calling setDaemon(true) before starting it.
  4. Low Priority: Daemon threads typically have lower priority than user threads.

25. What is thread priority?

Thread priority in Java determines the relative importance of a thread in the thread scheduling process. It is used by the JVM to decide when a thread should be given CPU time.

Key points:

  • Range: Thread priorities range from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) being the default.
  • Set by setPriority(): You can set the priority of a thread using setPriority(int priority).
  • Influence on scheduling: Threads with higher priority are more likely to be scheduled before lower-priority threads, but this is not guaranteed.

26. How to set the name of the thread?

     you can set the name of a thread using the setName() method or by passing a name when creating the thread.

  1. Using setName() :

                    Thread t = new Thread();

                     t.setName(“MyThread”);

2. During Thread Creation:

             Thread t = new Thread(“MyThread”);

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

The start() method in Java is used to begin the execution of a thread.

 Tasks performed by the start() method:

  1. Creates a new thread: It creates a new thread of execution in the JVM.
  2. Moves the thread to the Runnable state: After calling start(), the thread is ready to be scheduled by the JVM and may begin executing as soon as CPU time is available.
  3. Invokes the run() method: The run() method is automatically called by the JVM in the newly created thread.

28. What is the difference between the start() and run() method?

          Aspect             start()            run()
PurposeInitiates the execution of a new thread.Contains the code that the thread will execute.
FunctionalityCreates a new thread and invokes run() in that thread.Defines the task to be performed by the thread.
Thread CreationCreates a new thread and moves it to the Runnable state.Does not create a new thread; it runs in the current thread.
       UsageUsed to start the thread.Used to define the thread’s behavior.

29. Can we Overload run() method? What if we do not override the run() method?

Yes, you can overload the run() method by creating multiple versions with different parameters. However, the JVM will always call the no-argument run() method when starting the thread, even if you overload it.

If you do not override the run() method:

  • The thread will execute the default run() method from the Thread class, which does nothing.
  • The thread will not perform any task and essentially does nothing.

30. Can we Override the start() method?

No, you cannot override the start() method in Java because it is a final method in the Thread class. The start() method is responsible for creating a new thread and invoking the run() method, and overriding it would disrupt this behavior. If you need custom thread behavior, you should override the run() method instead.

Leave a Reply

Your email address will not be published. Required fields are marked *