Java Threading Question and Answers

9. What is the difference in using runnable and extends in threads?
 
  • Thread is a class and Runnable is an interface in java.
  • If a class is not extending another class we can use either extending Thread class or implementing Runnable interface.
  • If our class is already extending another class we can't extend Thread class because java doesn't support multiple inheritance so we have left only one choice that is implementing Runnable interface.
  • When you extend a thread each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.
 
Your Name Your Email-ID
Your Answer
10. What is wait() and notify()?
 
  • By using wait() and notify(), a thread can give up its hold on a lock at an arbitrary point, and then wait for another thread to give it back before continuing.
  • By executing wait () from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
  • Later, when the necessary event happens, the thread that is calls notify() from a block synchronized on the same object. Now the first thread wakes up and begins trying to acquire the lock again.
 
Your Name Your Email-ID
Your Answer
11. Can you explain Thread.sleep?
  Thread.sleep() is a static method of the Thread class that causes the currently executing thread to delay for a specified number of milliseconds. Below is the code snippet:
try
{
Thread.sleep ( 1000);
}
Catch ( InterruptedException e) {}
 
Your Name Your Email-ID
Your Answer
12. How can one thread wait for another thread to die before it continues execution?
  The thread’s join() method allows you to wait for another thread to finish execution.
 
Your Name Your Email-ID
Your Answer
1234567 Page 3 of 7