preloader

All multi-threading level questions such as thread ,process,synchronization ,join,thread priorities covered.

Multithreading

  • COURSES

    04 Month

  • DURATION

    03 Hours

Multi Threading is a process of running multiple thread at a same time consuming less memory and high performance.

what do you mean by Thread?

Thread is subset of process or lightweight sub-process
or
Threads can be used to perform complicated tasks in the background without interrupting the main program.

Difference between Thread and Process?

Thread Process
Thread is small subset of process Process is execution of program
Thread does not requires system resources Process requires system resources
Inter Thread communication is faster as they are dependent upon eachother Inter process communication is slow as they are independent

How to create Thread in application? Define different way of creating it?

Thread can be created in to two ways:

  • extends Thread class
  • implements Runnable interface

Extends Thread class

public class CreatingThread extends Thread{
            public void run() {
              System.out.println("Run Method using Thread class");
            }
           
           public static void main(String[] args) {
             CreatingThread thread = new CreatingThread();
             thread.start();
           }
         }

Implements Runnable interface

public class CreatingThread implements Runnable {
          public void run() {
              System.out.println("Run Method implements Runnable");
          }
          public static void main(String[] args) {
              CreatingThread thread = new CreatingThread();
              Thread th = new Thread(thread);
              th.start();
          }
      }

How extend thread and implements Runnable are difference from each other?

Extends Thread implements Runnable
further extends not possible further extends is possible
Tightly coupled Loosely coupled
Code Reusability is not possible Code Reusability is possible
execution will be slow execution is fast
Multiple inheritance is not support Multiple inheritance is support

Difference between User thread and Demon thread?

User Thread Demon Thread
Created by the application Created by the JVM
JVM waits JVM does not wait as created by JVM
Have high priority Have lowest priority
designed for specific task designed for support other thread

How to create Demon thread?

public class DemonNew extends Thread {
          public void run() {
              if (Thread.currentThread().isDaemon() == true) {
                  System.out.println("Demon Thread");
              } else {
                  System.out.println("User Thread");
              }
          }
          public static void main(String[] args) {
              DemonNew t1 = new DemonNew();
              DemonNew t2 = new DemonNew();
              t1.setDaemon(true);
              t1.start();
              t2.start();
          }
      }

Define Thread Scheduler?

Thread Scheduler is a component of Java that decides which thread to run or execute and which thread to wait. Every thread have priority of its own ,if there is more than one thread in the runnable state, it is up to the thread scheduler to pick one of the threads and ignore the other ones. There are two factors for scheduling a thread i.e. Priority and Time of arrival.
Priority: Priority of each thread lies between 1 to 10. Default priority of the thread is 5 If a thread has a higher priority, it means that thread has got a better chance of getting picked up by the thread scheduler.

  • public static int MIN_PRIORITY: It is the maximum priority of a thread. value of it is 1.
  • public static int NORM_PRIORITY: It is the normal priority of a thread. value of it is 5.
  • public static int MAX_PRIORITY: It is the minimum priority of a thread. value of it is 10

it can be changed any time after creation. We can check it by getPriority() method or setPriority() method for getting and setting the priority.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority cannot be the factor to pick a thread from these two threads. In such a case, arrival time of thread is considered by the thread scheduler. A thread that arrived first gets the preference over the other threads.

Difference between Preemptive scheduling and Time Slicing?

Preemptive scheduling Time Slicing
Under Preemptive scheduling high priority task executes until it enters the wait or dead states Under Time Slicing mechanism to divide the time into slice until re enter to ready task.

Difference Stage of Thread life Cycle?

Thread life Cycle have different Stage :

  • New
  • Runnable
  • Running
  • Waiting/Block
  • Sleep
  • Dead/Terminate

New: when thread is created ,it is in new state until thread call start() method.
Runnable : After starting thread will be in Runnable state until thread scheduler assign priority.
Running: After thread scheduler select thread for running i.e thread is selected for the execution by thread scheduler
Waiting/Block : State of thread is in waiting or block stage for monitor lock .Thread will be in this stage till notify() or notifyAll() method is called
Sleep : In this state thread is waiting at specific time allocated until timeout completed.
Terminated/Dead : Thread after execution completed will be moved to this state.

Difference between Start() and Run() method?

Run() Start()
run() is a method of Runnable
interface and also define
in java.lang package
start() method is defined
in thread class and
its package is java.lang.
run() method do not throws
any type of exception called
more than once
start() method can’t be invoked
more than once on same object
multiple call is possible in case
of run method.
otherwise it will
throw java.
lang run
IllegalThread
StateException
On other hand run method
executed by start method or
get called directly if we implement
Runnable interface and call run method.
As thread class implements Runnable
interface ,start method
internally called run method
after creating a new thread.
Defined in java.lang.Runnable interface
and must be overridden in
the implementing class.
Defined in java.lang.Thread class.

Difference between Wait() and Sleep() method?

Wait() Sleep()
The Wait() method is related to the Object class. The Sleep () method is related to the Thread class.
It is not a static method. It is a static method.
The Wait () method release the lock on the object during Synchronization The Sleep () method does not release the lock on the object during Synchronization.
The Wait() method has three overloaded methods The Sleep() method has two overloaded methods
  • Wait()
  • wait(long timeout, int nanoseconds)
  • wait(long timeout)
  • sleep(long milliseconds, int nanoseconds)
  • sleep(long milliseconds)

Can a thread called twice?

Thread can not be started twice once started can be executed till dead state. If called twice compiler produces runtime exception i.e. IlligalThreadStateException .

Define Join() method ?

Join() method is part of java.lang package.
Java allows one thread to wait until another thread completes its execution. In simpler words, it means it waits for the other thread to die. It has a void type and throws InterruptedException.
Joining threads in Java has three functions namely,

  • join()
  • join(long millis)
  • join(long millis, int nanos)
Syntax:
  • public final void join()
  • public final void join(long millis, int nanos)
  • public final void join(long millis)

Define Synchronization in Multithreading?

Synchronization is capability of control the access of multiple thread to any shared object resource in order to avoid data inconsistency.
Java Synchronization is better option where we want to allow only one thread to access the shared resource

Why use Synchronization?

The synchronization is mainly used to

  • To prevent thread interference.
  • To prevent consistency problem.

Types of Synchronization

  • Process Synchronization
  • Thread Synchronization

Define Deadlock in multithreading?

Deadlock is a situation in which all thread in waiting state are waiting for resource object but non of them get executed .Create universal waiting state and break the code at runtime.

To Avoid Deadlock:
  • use Join() method
  • Avoid the nested lock ()
  • Avoid the circular dependency
  • use Synchronization

Define between notify() and notifyAll()?

notify() notifyAll()
notify only one thread at a time notify multiple thread at a time
faster in execution since only one thread release at a time Slower in execution since multiple thread release at a time

Why Wait() ,notify() and notifyAll() present in Object class?

If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread and there is no way to know thread1 that thread2 was waiting for any resource to access. Hence, notify, wait, notifyAll methods are defined in object class in Java

why Sleep() and Yeild() method are static by nature ?

Sleep() and Yeild() method are static because it work on currently executing thread, rather than any specific thread – you don’t have to specify which thread is currently running to free up the processor.

Related Course

course thumb

Basic Java

All basic level question for java covered in this section for any one either experienced or fresher

Visit
course thumb

OOP Concept

Inheritance,Polimorphism,Abstraction and Encapsulation

Visit
course thumb

Exception handling

Exception handling ,it type ,error vs Exception

Visit