Java Thread Interview Questions And Answers

来源:互联网 发布:刷流量的软件 编辑:程序博客网 时间:2024/05/06 02:24

In this post we will see some of the most asked Java Thread interview questions with answers.

Q: What is a Thread?

A thread is a class in java belongs to java.lang package. A thread is an lightweight process and has its own call stack. In Java, you can run multiple threads parallely.  A thread is used to perform long running jobs dedicated without disturbing to the other part of program. Even if you don’t create any new threads in your program, there is at least one thread i.e. main thread() which runs the application.

Q: What is difference between thread and process?

  1. Threads share the address space of the process that created it; processes have their own address.
  2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  4. Threads have almost no overhead; processes have considerable overhead.
  5. New threads are easily created; new processes require duplication of the parent process.
  6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
  7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.

Q: What are the different states of a thread’s life cycle?

  1. New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
  2. Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
  3. Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
  4. Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

Q: What are the possible ways of creating thread?

There are two possible ways to create a thread in Java. One is by extending java.lang.Thread class and other is by implementing Runnable interface.

1. Extending Thread Class

In this process, just extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g.

public class MyThread extends Thread{  public void run(){ // Your code goes here // this code will be executed by NewThread }  public static void main(String [] args){      MyThread c = new MyThread();      c.start(); } }

2. Implementing Runnable Interface

Another way of creating thread is by implements the Runnable interface. The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class

public class MyThread implements Runnable{ public void run(){ //... }  public static void main(String [] args){     MyThread c = new MyThread();     Thread t = new Thread(c);     t.start(); } }

Q: What are different ways in which a thread can enter the waiting state?

A thread can enter the waiting state by the following ways:

  1. Invoking its sleep() method,
  2. By blocking on I/O
  3. By unsuccessfully attempting to acquire an object’s lock
  4. By invoking an object’s wait() method.
  5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q: What is the difference between yield and sleep?

When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q: Extending Thread class or implementing Runnable Interface. Which is better?

You have two ways to do so. First, making your class “extends” Thread class. The other way is making your class implement “Runnable” interface. The latter is more advantageous, cause when you are going for multiple inheritance, then only interface can help. . If you are already inheriting a different class, then you have to go for Runnable Interface. Also, if you are implementing interface, it means you have to implement all methods in the interface.

Both Thread class and Runnable interface are provided for convenience and use them as per the requirement. But if you are not extending any class, better extend Thread class as it will save few lines of coding. Otherwise performance wise, there is no distinguishable difference. A thread is in the ready state after it has been created and started.

Q: What is mutual exclusion? How can you take care of mutual exclusion using Java threads?

Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code.

There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Q: What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Q: What invokes a thread’s run() method?

After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

Q: What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-communication.

Q: What is deadlock?

When two threads are waiting for each other and can’t proceed until the first thread obtains a lock on the other thread or vice versa, the program is said to be in a deadlock.

Q: What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method 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.

Q: What is a volatile keyword?

In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

Q: What’s the difference between the methods sleep() and wait()?

The sleep method is used when the thread has to be put aside for a fixed amount of time. Ex: sleep(1000), puts the thread aside for exactly one second. The wait method is used to put the thread aside for up to the specified time. It could wait for much lesser time if it receives a notify() or notifyAll() call. Ex: wait(1000), causes a wait of up to one second. The method wait() is defined in the Object and the method sleep() is defined in the class Thread.

Q: What is the difference between process and thread?

A thread is a separate path of execution in a program. A Process is a program in execution.

Q: What is daemon thread and which method is used to create the daemon thread?

Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon()

When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.

Q: What do you understand by Synchronization?

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.

E.g. synchronizing a function:

public synchronized void Method1 () {// method code.}

E.g. synchronizing a block of code inside a function:

public Method2 (){synchronized (this) {// synchronized code here.}}

Q: When will you synchronize a piece of your code?

When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method.

Q: Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

Q: Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.

Q: What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

Q: Is there a separate stack for each thread in Java?

Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory.

Elements of the stack are the method invocations, called activation records or stack frame. The activation record contains pertinent information about a method like local variables.

Q: What is the difference between yield() and sleep()?

yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.

sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.

Q: What is the difference between wait() and sleep()?

1) wait() is a method of Object class. sleep() is a method of Object class.

2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

Q: What is difference between notify() and notfiyAll()?

notify( ) wakes up the first thread that called wait( ) on the same object.

notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first

Q: If a thread goes to sleep does it hold the lock?

Yes when a thread goes to sleep it does not release the lock.

Q: Can a thread hold multiple locks at the same time?

Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the synchronized method / block, it may call another synchronized method and acquire a lock on another object.

Q: Can a thread call multiple synchronized methods on the object of which it hold the lock?

Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds.

Q: Can static methods be synchronized?

Yes. As static methods are class methods and have only one copy of static data for the class, only one lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this instance is used to synchronize the static methods.

Q: Can two threads call two different static synchronized methods of the same class?

No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.

Q: Does a static synchronized method block a non-static synchronized method?

No As the thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called, these two locks are different and these threads do not block each other.

Q: Once a thread has been started can it be started again?

No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown, which is a runtime exception. A thread in runnable state or a dead thread can not be restarted.

Q: Can the start() method of the Thread class be overridden?

Yes the start() method can be overridden. But it should not be overridden as its implementation in thread class has the code to create a new executable thread and is specialized.

Q: What are the methods of the thread class used to schedule the threads?

The methods are as follows:

  1. public static void sleep(long milliseconds) throws InterruptedException
  2. public static void yield()
  3. public final void join() throws InterruptedException
  4. public final void setPriority(int priority)
  5. public final void wait() throws InterruptedException
  6. public final void notify()
  7. public final void notifyAll()

Q: Which thread related methods are available in Object class?

The methods are:

  1. public final void wait() throws Interrupted exception
  2. public final void notify()
  3. public final void notifyAll()

Q: Which thread related methods are available in Thread class?

Methods which are mainly used :

  1. public static void sleep(long milliseconds) throws Interrupted exception
  2. public static void yield()
  3. public final void join() throws Interrupted exception
  4. public final void setPriority(int priority)
  5. public void start()
  6. public void interrupt()
  7. public final void join()
  8. public void run()
  9. public void resume()

Q: List the methods which when called the thread does not release the locks held?

  1. notify()
  2. join()
  3. sleep()
  4. yield()
0 0
原创粉丝点击