This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SCJP 1.6 ...Threads. Needs clarification of a Self Test ans from K&S Book

 
Sumeet Chakraborty
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ..




 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic