File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to access variable from run() method

 
Amee Dabo
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have reader.java class file
readResult extends Thread

I am calling readResult from reader.java as follows:
//pt.1
for (int i=0; i<10; i++)
readResult rd = new readResult();
rd.start();
}
//pt.2

I am doing some processing in run() method of readResult.java & setting a flag in run method in a while loop.

What I want to do is:

After pt.1 to pt.2 is executed in a loop, & if flag=false then I want to display a message after pt.2The ques I am facing is How Should I access this flag which is ggeting set in run() method in my file?

Thanks a lot..
Ameeta
 
Clifton Craig
Ranch Hand
Posts: 103
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First you want to rename readResult to ReadResult to follow Java naming convention, making your object more usable and attractive to other developers. Then you want to cache the ReadResult objects in a collection. Within ReadResult.java you'll need to define public accessors for the flag, a public boolean isFinished() method would suffice. I'm assuming the flag indicates completion of the run method. The flag should be defined in ReadResult as an instance variable, not static. That will give each thread its own copy of the value. In your loop at pt2, you will loop on the condition collection.empty() and check the value of the flag in each thread within the loop. If the value is what you'd expect you will remove that thread from the collection.

[ June 12, 2006: Message edited by: Clifton Craig ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look into join() as a more efficient way to know when your threads are done.

I played with some ideas to do one loop at the end instead of two, but it wound up with circular references between Thread and MyRunnable. Any other thoughts?

See also FutureTask. In JDK 5 or later it does all this for you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic