| Author |
SCJP 1.6 ...Threads. Needs clarification of a Self Test ans from K&S Book
|
Sumeet Chakraborty
Ranch Hand
Joined: Feb 05, 2009
Posts: 45
|
|
I am not able to get a clear explanation of the ans of the following question (Kathy Siera , Threads , Q.No 16).
Can anyone help me understanding the answer ... ?
Given
class Chicks {
synchronized void yack(long id){
for(int x=1; x<3; x++){
System.out.print(id +" ");
Thread.yield();
}
}
}
public class ChicksYack implements Runnable {
Chicks c;
public static void main(String[] args){
new ChickYack().go();
}
void go(){
c=new Chicks();
new Thread(new ChickYack()).start();
new Thread(new ChickYack()).start();
}
public void run(){
c.yack(Thread.currentThread().getId());
}
}
Which are true ?
A. Compilation Fails
B. The output could be 4 4 2 3
C. The output could be 4 4 2 2
D. The output could be 4 4 4 2
E. The output could be 2 2 4 4
F. An exception is thrown at runtime.
F is correct. When run() is invoked, it is with a new instance of ChicksYack and c has not been assigned to an object......
Can anyone explain me the above ?
|
 |
Cristian Senchiu
Ranch Hand
Joined: Feb 08, 2009
Posts: 40
|
|
Let's use only the relevant (for your question) part of code ( formatted so it's easier to read):
The two threads you start at line 11 and 12 do not use your current ChickYack instance you create at line 10.
Each creates its own, new instance: new Thread(new ChickYack()) ...
Since c is only declared (line 3) => it has the default value which is null.
That means, at line 16 c is null => a NullPointerException will be thrown.
|
 |
Sumeet Chakraborty
Ranch Hand
Joined: Feb 05, 2009
Posts: 45
|
|
Thanks for your reply .... I think i got the explanation.
Since it creates entirely new objects(in line 11,12) c will be null for these objects.
Thanks again ..
|
 |
 |
|
|
subject: SCJP 1.6 ...Threads. Needs clarification of a Self Test ans from K&S Book
|
|
|