Java Threading Interview Questions and Answers for Experienced - 2

Question: 6

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.

Question: 7

How to stop a thread?

thread.stop;

Question: 8

Can you explain Yielding in threading?

It causes the currently executing thread object to temporarily pause and allow other threads to execute.

Question: 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.

Question: 10

What are monitors?

Monitor is a body of code which can be executed by only one thread at a time. If any other thread tries to get access at the same time, it will be suspended until the current thread releases the monitor.

Related Questions