my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question" Watch "Thread Question" New topic

Thread Question

Rex Rodriguez

Joined: Jan 16, 2002
Posts: 21
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

Joined: Nov 30, 2001
Posts: 102
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);
} catch(InterruptedException ie){}
System.out.println(tc.x); // Now prints 10
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
Very good explanation Jennifer!


SCJP 1.4
I agree. Here's the link:
subject: Thread Question
It's not a secret anymore!