aspose file tools*
The moose likes Threads and Synchronization and the fly likes How to access variable from run() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to access variable from run() method" Watch "How to access variable from run() method" New topic
Author

How to access variable from run() method

Amee Dabo
Ranch Hand

Joined: Dec 22, 2001
Posts: 74
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


Thanks..
Clifton Craig
Ranch Hand

Joined: May 26, 2006
Posts: 103
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 ]

Holla at me...<br /><a href="http://codeforfun.wordpress.com" target="_blank" rel="nofollow">http://codeforfun.wordpress.com</a>
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to access variable from run() method