Posted by
Many people feel that Threads and Collection APIs are somewhat complex areas in Java. At least, this is true when you go for Java interviews. If the interviewer wants to screw you more, then he may ask bunch of questions from Threads and Collections APIs. I came up with some (scenario based) Java Thread questions and answer. Enjoy!
QUESTIONS
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).
2. What happens when a thread calls notify() but no thread(s) is waiting?
3. How will you declare a timer variable that will be accessed by multiple threads very frequently?
4. How will you synchronize static variables?5. What happens when threads are waiting, but never being notified?
ANSWERS:
1. 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()
2. Actually…, nothingthe notify() call simply returns.
3. 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.
4. Obtain class level lock. synchronized( obj.getClass()) {……..}
5. Leaving the answer to readers!![]()
Related posts:
Related posts brought to you by Yet Another Related Posts Plugin.
asdas
Very very informative. Thanks very much.