• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread Question

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}
}
 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Very good explanation Jennifer!

Rob
 
reply
    Bookmark Topic Watch Topic
  • New Topic