Multithreading in Java Interview Questions and Answers
by Bhavya Sri, on Mar 15, 2018 12:07:11 PM
Q1. What is Thread in java?
Ans: Threads consumes CPU in best possible manner, hence enables multi processing. Multi threading reduces idle time of CPU which improves performance of application.
- Thread are light weight process.
- A thread class belongs to java.lang package.
- We can create multiple threads in java, even if we don’t create any Thread, one Thread at least do exist i.e. main thread.
- Multiple threads run parallely in java.
- Threads have their own stack.
- Advantage of Thread : Suppose one thread needs 10 minutes to get certain task, 10 threads used at a time could complete that task in 1 minute, because threads can run parallely.
Q2. What is Multithreading?
Ans: The process of executing multiple threads simultaneously is known as multithreading. Java supports multithreading. The main advantage of multithreading is reducing CPU idle time and improving the CPU utilization. This makes the job to be completed in less time.
Q3. What is difference between Process and Thread in java?
Ans: One process can have multiple Threads,
Thread are subdivision of Process. One or more Threads runs in the context of process. Threads can execute any part of process. And same part of process can be executed by multiple Threads.
Processes have their own copy of the data segment of the parent process while Threads have direct access to the data segment of its process.
Processes have their own address while Threads share the address space of the process that created it.
Process creation needs whole lot of stuff to be done, we might need to copy whole parent process, but Thread can be easily created.
Processes can easily communicate with child processes but interprocess communication is difficult. While, Threads can easily communicate with other threads of the same process using wait() and notify() methods.
In process all threads share system resource like heap Memory etc. while Thread has its own stack.
Any change made to process does not affect child processes, but any change made to thread can affect the behavior of the other threads of the process.
Example to see where threads on are created on different processes and same process.
Q4. How to implement Threads in java?
Ans: This is very basic threading question. Threads can be created in two ways i.e. by implementing java.lang.Runnable interface or extending java.lang.Thread class and then extending run method.
Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution is an individual process that has its own call stack. Thread are lightweight process in java.
Thread creation by implementingjava.lang.Runnableinterface.We will create object of class which implements Runnable interface :MyRunnable runnable=new MyRunnable(); Thread thread=new Thread(runnable); And then create Thread object by calling constructor and passing reference of Runnable interface i.e. runnable object : Thread thread=new Thread(runnable);
Q5. What are the two ways of creating a thread?
Ans: We can create a thread by using any of the two following methods.
1) By implementing Runnable interface
2) By extending Thread class
Q6. How to make a thread (user thread) to Daemon thread?
Ans: By calling setDaemon() method we can make a user thread to daemon thread.
Syntax:
thread.setDaemon(true);
Q7. What is difference between user thread and Daemon thread?
Ans: By default a thread created in a program is always a user thread, however we can make it daemon by calling setDaemon(true) method, if needed. A daemon thread runs in a background and it doesn’t prevent JVM from being shutdown. Once all the user thread gets completed the JVM shutdowns without being bothered whether a daemon thread is running or not.
Q8. Can we change a user thread to deamon thread by calling setDaemon() method if the thread has already been started?
Ans: No, if the thread has been started then we cannot make it daemon because it would then throw an IllegalThreadStateException
Q9. When threads are not lightweight process in java?
Ans: Threads are lightweight process only if threads of same process are executing concurrently. But if threads of different processes are executing concurrently then threads are heavy weight process.
Q10. How threads communicate between each other?
Ans: This is very must know question for all the interviewees, you will most probably face this question in almost every time you go for interview.
Threads can communicate with each other by using wait(), notify() and notifyAll() methods.
Q11. Can we call run() method of Thread class?
Ans:We can call run() method if we want but then it would behave just like a normal method and we would not be able to take the advantage of multithreading. In general run() methods starts execution when we call start() method of a Thread class. For more details on this: Refer this article.
Q12. What is deadlock?
Ans: A deadlock is a condition when two or more threads are in waiting for each other to release the resources that they need. For example Thread A holds a resource X and need resource Y whereas Thread B holds a resource Y and need X, in this case both threads are waiting for each other to release the resource and are in blocked condition.
Q13. What is synchronization?
Ans: It is a technique of granting access to the shared resources in multithread environment to avoid inconsistencies in the results.
Q14. What is the difference between notify() and notifyAll()?
Ans: notify() wakes up the first thread that called wait() on the same object, whereas the notifyAll() method wakes up all the waiting threads.
Q15. What does join() method do?
Ans: The join() method is used to hold the execution of currently running thread until the specified thread is dead(finished execution).
Read more about join() here.
Q16. Can we start a thread twice in Java?
Ans: No, once a thread is started, it can never be started again. Doing so will throw an illegalThreadStateException. For example: Refer this article.
Q17. Is it important to acquire object lock before calling wait(), notify() and notifyAll()?
Ans: Yes, it’s mandatory to acquire object lock before calling these methods on object. As discussed above wait(), notify() and notifyAll() methods are always called from Synchronized block only, and as soon as thread enters synchronized block it acquires object lock (by holding object monitor). If we call these methods without acquiring object lock i.e. from outside synchronize block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait() method needs to enclosed in try-catch block, because it throws compile time exception i.e. InterruptedException.
Q18. Are you aware of preemptive scheduling and time slicing?
Ans: In preemptive scheduling, the highest priority thread executes until it enters into the waiting or dead state.
In time slicing, a thread executes for a certain predefined time and then enters runnable pool. Than thread can enter running state when selected by thread scheduler.
Q19. As stop() method is deprecated, How can we terminate or stop infinitely running thread in java? (Important)
Ans: Answer. This is very interesting question where interviewees thread basics basic will be tested. Interviewers tend to know user’s knowledge about main thread’s and thread invoked by main thread.
We will try to address the problem by creating new thread which will run infinitely until certain condition is satisfied and will be called by main Thread.
- Infinitely running thread can be stopped using boolean variable.
- Infinitely running thread can be stopped using interrupt() method.
Let’s understand Why stop() method is deprecated :
Stopping a thread with Thread.stop() causes it to release all of the monitors that it has locked. If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, which might lead to unpredictable behavior.
Q20. Does thread leaves object lock when sleep() method is called?
Ans: When sleep() method is called Thread does not leaves object lock and goes from running to waiting state. Thread waits for sleep time to over and once sleep time is up it goes from waiting to runnable state.
Q21. Does thread leaves object lock when wait() method is called?
Ans: When wait() method is called Thread leaves the object lock and goes from running to waiting state. Thread waits for other threads on same object to call notify() or notifyAll() and once any of notify() or notifyAll() is called it goes from waiting to runnable state and again acquires object lock.
Related Interview Questions...
Core Java Interview Questions And Answers
Core Java Programming Interview Questions and Answers
Java Interview Questions and Answers
Javascript Interview Questions
Java/J2EE Apps Integration Questions and Answers.
Java Collections Interview Question and Answers
Interview Questions For Selenium with Java