Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

output of this program from certification book

 
amar nath jha
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This program is from A Programmer's Guide to Java Certification (Second Edition ) by khalid A. Mughal and Rolf W. Rasmussen from Chapter Thread.Please help me to solve this .

public class Joining
{
static Thread createThread(final int i ,final Thread t1)
{
Thread t2 = new Thread(){
public void run(){
System.out.println(i+1);
try{
t1.join();
}
catch(InterruptedException e){}
System.out.println(i+2);
}
};
System.out.println(i+3);
t2.start();
System.out.println(i+4);
return t2;
}
public static void main(String[] args){
createThread(10,createThread(20,Thread.currentThread()));
}
}
..............................
option are :
a)The first number printed is 13
b)The number 14 is printed before the number 22
c)The number 24 is printed before the number 21
d)the last number printed is 12
e)The number 11 is printed before the number 23

correct option is b and d. How ?
 
Praveen Balaji
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Difficult to explain this on a forum, but I'll try.

The BEST way to figure how the execution happens is by naming the threads and debugging through the code. You'll see multiple threads being created and figure out which steps can be executing parallely.

Remember that with paralelly executing threads, it's often difficult to predict the order of execution. There are some synchronization constructs, however, that can assure a "happens-before" relationship between instructions. You should look up the JSR-133.

Having said that, here is an attempt to answer your question. I have broken up the code in the main method.



I'm sure it's confusing. But that's the way with threads. As one of the senior programmers at my previous company said: "Threads are like snakes. Dont use them if you dont have to".




PS: If it interests you: the more I think about it, the more I seem to believe that the world is single-threaded and procedural. It's like a see-saw. One end goes up and the other goes down. If you look at it separately, they are two events happening parallely.
The world is probably single threaded: think about parallel universes - the see-saw of the universe.

[ November 27, 2006: Message edited by: praveen balaji ]
[ November 27, 2006: Message edited by: praveen balaji ]
 
amar nath jha
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply .you really made it very easy to understand.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic