• 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

Pls help me out of this tangle

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class An extends Thread
{
private int i;
public void run()
{
i = 1;
}
public static void main(String[] args)
{
An a = new An();
a.start();
System.out.print(a.i);
}
}



Hai when i invoke this program it is giving output as 0.But my expectation is 1.Why it is giving like this.

pls genius help me to understand the concept behind this program.

thanks,
jaijai
 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are assuming that the start() method invokes and completes a.run() before the System.out.println( a.i ) is executed. However, you have no control over thread scheduling, so what's happening here is that System.out.println( a.i ) is executing before the run() method.

To confirm this, add the following line to the An run method:


Here, you'll see:



Note the '0' before the run print statement.

Hope that helps...
 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

If you wanted to make sure that you only continued processing AFTER the thread had finished running (that is dead), you could use the "join" method as below. Thus the main thread would wait until the "a" thread had finished before executing "System.out.print(a.i);"

public class An extends Thread
{
private int i;
public void run()
{
i = 1;
}
public static void main(String[] args) throws InterruptedException
{
An a = new An();
a.start();
a.join();
System.out.print(a.i);
}
}

Cheers,

Simon.
 
Jeff Bosch
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great point, Simon. Thanks for adding that. I had only told half the story; join() is very important as it's really about the only control you have over thread scheduling. (I'm not counting wait() and sleep()...)
[ March 23, 2005: Message edited by: Jeff Bosch ]
reply
    Bookmark Topic Watch Topic
  • New Topic