Saturday, May 9, 2009

Java Interview Questions: Threads I

Q1. Can we call the run() method instead of start() ?

Ans. Yes, we can do that. But, this will not start a new thread. The contents of the run method will be executed just as a method call, in the existing thread. If you want to start a new thread, you should call the start() method only. The start() method will, in turn call the run() after creating a new thread of execution.

Q2. Why is the sleep method static ?

Ans. There are many static methods in the Thread class. They all operate on the current thread, that is, the thread that executes the method. You cannot perform these operations on other threads.

Q3. What are daemon threads?

Ans. Daemon threads are nothing but a very low priority threads. They have no particular role, other than helping the other threads. When only daemon threads remain, then the program exits.

Q4. What is the default priority of a newly created thread?

Ans. NORM_PRIORITY or 5.

Q5. What are the two ways of creating a new thread?

Ans. 1. Extending the Thread class    2. Implementing the runnable interface

Q6. What are the four states associated with a thread?

Ans. new   runnable    blocked    dead

Q7. What happens if we call start() on a thread object which is already started?

Ans. Nothing will happen. A thread can only be started once. After that, even if in a dead state, a thread cannot be re-started. Calling the start method again will cause an exception (IllegalThreadStateException), a kind of RuntimeException.

Q8. What does yield() method do?

Ans. This method makes the current running thread move to runnable, to allow other threads of the same priority get their chance. A yield() call will never send a running thread to waiting/sleep/blocking state. At the most, the current thread will go to runnable thread. But again, if there are no other threads to run, this thread might again be picked up by the scheduler, thus having no superficial effect at all. That is, it is as good as, that the call was never made.

Q9. What does join() call do?

Ans. When it is required that a thread, say A, cannot proceed before the completion of another thread say, B, then we ask the thread A to join B. By doing so, we are telling A, to proceed only when the thread B has finished it’s job.

Q10. Why should we avoid unnecessary Synchronisation?

Ans. Synchronisation prevents concurrent execution. Thus, when a thread is inside a synchronised method, other threads cannot enter that method. While,the main objective of multi-threading is to allow concurrency, synchronisation prevents it. So, only when absolutely necessary, we should use synchronisation.

No comments: