This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Question

 
Rex Rodriguez
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following program prints 10 and 5. I understand the first value printed;i.e.10 but I am not clear why it is printing 5 in the second print statement rather than 10. Thanks in advance for any helps.
public class test implements Runnable
{
int x = 5;
public void run()
{
this.x = 10;
}
public static void main(String[] args)
{
test tc = new test();
System.out.println(tc.x); // First value of tc.x
new Thread(tc).start();
System.out.println(tc.x); // Second value of tc.x
}
}
 
Jennifer Wallace
Ranch Hand
Posts: 102
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The program prints 5 for the first print statement because that is the value of the member variable x .

After the thread is started, the second print statement wud print 10 or 5 depending on which thread is executed first (the main thread or the newly started thread).
When I tried I got 5 only.
To just show that the same field is being modified, I tried putting the join statement in the code. Now the main thread is executed only after the child thread is completed.So it prints 10.

System.out.println(tc.x); // first print..prints 5
Thread t=new Thread(tc);
t.start();
try{
t.join();
} catch(InterruptedException ie){}
System.out.println(tc.x); // Now prints 10
}
 
Rob Ross
Bartender
Posts: 2205
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very good explanation Jennifer!

Rob
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic