Threads interview questions and answers in java

In this page we will come to know most of the threads interview questions and answers. If any one has faced any of the other questions which is not mentioned in the current page. Please share with me through "Contact me here" gadget which is present in end of the page or drop me an email to "admin@javatbrains.com".
 
Q1: How many ways you can create a Thread?A: Mainly two ways we can create Thread class.
  1. Extending Thread class
  2. implementing Runnable Interface
Q2: Can you explain about these two ways to create a Thread?
A: The first method of creating a thread class is to simply extend from the Thread class. This should be done if the class does not ever need to be extended from another class.

              import java.lang.*;

              public class Count extends Thread{
                     public void run(){
                            .....
                     }
              }

        The above example creates anew class Count that extends the Thread class and overrides the Thread.run() method. The run() method is where all the work of the Count class thread is done. The same thread class can be created by implementing the interface Runnable.

              import java.lang.*;
              public class Count implements Runnable{
                    Thread t;
                    public void run(){
                          .....
                    }
             }

        Here, the abstract run() method is defined in the Runnable interface and is being implemented. Note that we have an interface of the Thread class as a variable of the Count class. The only difference between the two methods is that by implementing Runnable, there is greater flexibility in the creation of the class Count. In the above example, the opportunity still exists to extend the Count class, if needed. So, use implements Runnable is better for creating Thread.

        An interface only provides a design upon which classes should be implemented. In the case of the Runnable interface, it forces the definition of only the run() method.

Q3: What does Thread.start() do?
A: The start method creates the system resources necessary to run the thread and schedules the thread to run. After the start method has returned, the thread is actually in the Runnable state. When a thread gets the CPU time, it will executed.

Q4: What is Scheduling? How is a thread Prioritized?
A: Execution of multiple threads on a single CPU, in some order, is called scheduling. The java runtime supports a very simple, deterministic scheduling algorithm known as fixed priority scheduling.This algorithm schedules thread based on their priority relative to other runnable threads.

        When a java thread is created, it inherit its priority from the thread that created it. You can also modify a threads priority at anytime after creation using the setPriority(). Thread priorities are integers ranging between MIN_PRIORITY(1) and MAX_PRIORITY(10). The value 5 is the default priority(NORM_PRIORITY). The higher the integer, the higher the priority. At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution. Only when that thread stops, yields or becomes not runnable for some reason will a lower priority thread start executing. If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a Round-Robin fashion.

        The chosen thread run until one of the following conditions is true:
  • A higher priority thread becomes runnable.
  • It yields, it run method exists.
  • On systems that supports time-slicing. its time allotment has expired.
        Then second thread is given a chance to run, and so on, until the interpreter exists.

Q5: What is the difference between yielding and sleeping in threads?A: when a thread invokes it's yield() method, it returns to the ready state.
When a thread invokes its sleep() method, it returns to the waiting state.

Q6: What is the difference between preemptive scheduling and time slicing?A: Under preemptive scheduling, the highest priority thread executes until it enters the waiting or dead states or a higher priority thread comes into existence. Under time slicing, a thread executed for a predefined slice of time and then re-enters the pool of ready threads. The scheduler then determines which thread should execute next, based on priority and other factors.

Q7: What are synchronized methods and synchronized statements?A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized methods after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. 

        A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. This means that no other thread can access the object till the current thread releases the object. This is used to make code thread safe & prevent dirty reads.

Q8: When do you use synchronized statements?A: Synchronized statements are good to use when
  • it is sufficient to synchronize only a part of the method
                 void method(){
                       //some statement
                       synchronized(this){
                            this.a = 20;
                      }
                      //some statement
                 }
  • If a class whose object to be locked is part of a third party jar file
                void method(){
                      //some statements
                      synchronized(thirdPartyobject){
                             thirdPartyobject.a = 20;
                       }
                      //some statement
                 }

Q9: How can a dead thread be restarted?
                       (or)
Is is possible to restart a dead thread?

A: A dead thread cannot be restarted.

Q10: what invokes a thread's run() method?
                          (or)
How the run() method will execute in a thread?

A: After a thread is started, via its start() method or that of the Thread class, the JVM scheduler invokes the thread's run() method once the turn comes for the thread to run.

Q11: When do threads go out of runnable state?
                           (or)
When thread will come out of runnable state?

A: A thread becomes Not Runnable when one of these events occurs:
  • Its sleep method is invoked.
  • The thread calls the wait method to wait for a specific condition to be satisfied.
  • The thread is blocking on I/O.
Q12: What is a monitor?A: A monitor is a lock on an object which allows only one thread to access/modify the contents of that object.

Q13: How do you make code thread safe?A: The keyword synchronized is used to temporary lock an object to have exclusive access to it. It marks a block of code or an entire method as critical section. Only one thread can execute it at any point in time. Other threads will wait for their turn to use the critical section.

        when an instance method is synchronized, the synchronized code can be run by many threads on different objects simultaneously, since the locking is on the object. For a synchronized class method, the locking is on the class object, which thus limits to only one thread executing that code.

Q14: what does Thread.wait() do?A: Thread.wait() and Thread.notify() methods are used for inter-thread communication. Thread.wait() makes the thread go to sleep until some other thread wakes it up using Thread.notify() or Thread.notifyAll() methods.

        The wait method is defined in the Object class. Since all classes in java extend Object by default, it is available in all classes.


Q15: What is a daemon thread?A: Daemon thread are sometimes called 'Service' threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced.

        The garbage collector thread is an example of a daemon thread. This thread, provided by the JVM, will scan programs for variables that will never be accessed again and free up their resources back to the system.

        A thread can set the daemon flag by passing a true boolean value to the setDaemon() method. If false boolean value passed the thread will become a user thread. However, this must occur before the thread has been started.

        The JVM scheduler's basic rule is if there are only Daemon Threads running, the Java Virtual Machine(JVM) will exit.

Q16: What is the difference between notify() and notifyAll()?
A: notify(): This can be only from with in synchronized method/block. It wakes up a single thread which is waiting on the objects lock. If there is more than one thread is waiting, the choice is arbitrary i.e. there is no way to specify which waiting thread should be awakened.

   notifyAll(): wakes up all the waiting threads. The JVM scheduler will then decide which thread will run.

Related Posts:

Comments

Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example