Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for loop issue in thread application

 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

I was coding and testing out a simple thread application when I realised that for some reason the program does not enter the for loop when it's supposed to. I am not sure why. I have placed print statements at selected points in both the java files to monitor the program flow, I can safely say the program execution goes all the way into the run method, but not into the for loop within the run method. I am not sure why, to me everything seems to be in order. Hope some can advise. Thanks.



NumberFinderThreadApp



Finder
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can you guess what this code is doing ?
 
Indrayani Godbole
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi John,
I checked your code and found that Finder class constructor needs a change

your original constructor is :

Finder(int target, int begin, int end)
{
//Test
System.out.println("Finder constructor");
//end test

target = target;
begin = begin;
end = end;

}

here, you should initialize the field members begin and end as follows :


this.begin = begin;
this.end = end;

this will initialize your class field members begin and end which you are using in run method.

currently what is happening is, local variables begin and end of the constructor are getting initialized and so when run method is accessing the begin and end field members for the For loop, it is getting 0 values for both since they were not initialized through constructor.
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you are actually working with variables local to your constructor, and class fields are left uninitialized.

@indrayani gd: Please UseCodeTags.
 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

Thanks for the replies. Yes, 'this' does the trick. Thanks.

regards
John
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic