Sunday, January 31, 2010

Java Threads Interview Questions

Question 1:. Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).



Answer:-Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()


Question 2:What happens when a thread calls notify() but no thread(s) is waiting?


Answer:-Actually…, nothing the notify() call simply returns.


Question 3:How will you declare a timer variable that will be accessed by multiple threads very frequently?


Answer:-Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.


Question 4:How will you synchronize static variables?


Answer:-
Obtain class level lock.
synchronized( obj.getClass()) {……..}

Question 5:What happens when threads are waiting, but never being notified?

No comments:

Post a Comment