Java Interview question -3
Question: How can i tell what state a thread is in ?
Answer: Prior to java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.
Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.
NEW | A Fresh thread that has not yet started to execute. |
RUNNABLE | A thread that is executing in the Java virtual machine. |
BLOCKED | A thread that is blocked waiting for a monitor lock. |
WAITING | A thread that is wating to be notified by another thread. |
TIMED_WAITING | A thread that is wating to be notified by another thread for a specific amount of time |
TERMINATED | A thread whos run method has ended. |
Question: What methods java providing for Thread communications ?
Answer: Java provides three methods that threads can use to communicate with each other: wait, notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is that a method called by a thread may need to wait for some condition to be satisfied by another thread; in that case, it can call the wait method, which causes its thread to wait until another thread calls notify or notifyAll.
Question: What is the difference between notify and notify All methods ?
Answer: A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll than notify).
Comments
soon i will give the solution of all these questions ,