Saturday, March 6, 2021

Multi-Threading

 Q1. What is Thread?

Ans:  Thread is a lightweight sub-process. it create by using extends Thread class and Implement Runnable interface.

Q. Why do we use Multithreading?

Ans: 

Q. What is Thread Lifecycle in Java?

Ans: Before moving on to creating a thread, we’ll first see the various phases through which the thread has to pass to complete its lifespan.

  • New
  • Runnable
  • Running
  • Non-Runnable (blocked)
  • Terminated



New- A thread is in New state when you create the instance of thread class, but the start() method is yet to get called.

Runnable- The thread is in runnable after executing the start() method. In this stage, it waits for the thread scheduler to run it.

Running- A thread picked by the thread scheduler for execution remains in running state.

Non-Runnable (blocked)- In this state, the thread remains alive, but it is not eligible to run. It may be due to some sleep operation, waiting for any File I/O to finish or in the locked state, etc.

Terminated- A thread is said to be in the terminated state when it’s Run() method exits.


wait() - Tells the current thread to release the lock and go to sleep until some other thread enters the same monitor and calls notify().

notify() - Wakes up the single thread that is waiting on this object's monitor.

notifyAll() - It wakes up all the threads that called wait() on the same object.

Synchronization:- 1. Synchronized is the keyword applicable for methods & blocks but not for classes and variables.

2. If a method or block declared as the Synchronized then at a time only one thread is allow to execute that method or block on the given Object.

3. The main advantages of synchronized keyword is we can resolve data inconsistency problems.

4. But the main disadvantage of synchronized keyword is it increases waiting time of the thread and effects performance of the system.

No comments:

Post a Comment

String coding questioon

  How do you reverse a given string in place? ( solution ) How do you print duplicate characters from a string? ( solution ) How do you chec...