Wednesday, September 24, 2008

Interview Q & A: Java Threads

#1 What is daemon thread and How will you create a daemon thread?

Daemon threads are low priority threads running in background. By calling setDaemon(true), we can make a thread daemon. GC in java is a good exampe for daemon thread.

#2 What are different ways in creating a thread and which is recommended?

There are two ways to create a thread:

* By Implementing Runnable interface (recommended) and implementing run() method
* By extending Thread class and implementing run() method

#3 Explain thread life-cycle?

* Ready state: Whenever a Thread is created, it reaches the ready state. start() method puts the thread in ready state.
* Running state: run() method called automatically by the start() method moves the thread from ready state to running state.
* Blocked/Wait state: wait() and sleep() methods moves the thread from running state to blocked state. By calling notify() or notifyAll() and yield() method will make them again move to ready state.
* Dead state: Thread moves to dead state after completion of run() method.

#4 What do you mean by Thread Synchronization?

Thread synchronization allows only one thread to execute at a time in a multithreaded environment. We can either have a method synchronized or a synchronization block.

#5 What is the Default priority of Thread?

NORM_PRIORITY is the default priority of a Thread.

#6 What is deadlock? How do you prevent it?

Deadlock is a condition at which two processes are waiting for each other to complete before proceeding. It is a cyclic dependency where one should take care to prevent such scenarios and no API methods are available to prevent it.

No comments: