Click to See Complete Forum and Search --> : Return data from thread in Java


emus
06-05-2003, 07:06 PM
How can I return data from a thread?


public class Reader extends Thread
{
String finalStr;

public void run()
{
until EOF
read data from file and append
to string buffers

finalStr=stringBuffer.toString();
}

public String finalize()
{
return(finalStr);
}
}


If I call System.out.println(finalize()); from my main class, I won't get the desired output since the Thread won't have finished. How can I ensure that the thread finishes before the result is printed out? If I tell the thread to yield after starting it, it works sometimes, but not always.
Does anyone know the correct method of returning data from a trhead?

Thanks,

emus

bwkaz
06-05-2003, 10:32 PM
Set up an array of strings, one for each thread, plus an array of booleans, one for each thread (initialized to false). When the thread finishes, have it write its string into the first array, then set its boolean to true in the second array.

In the main program, read the second array, and whenever an entry goes from false->true, read the corresponding string out of the first array.

You might want to make these arrays thread-protected, too, though it may not matter. I think you use a "synchronous" keyword in the definition in Java to do that.

emus
06-06-2003, 12:53 AM
Thank you, I'll try that.

Stuka
06-06-2003, 09:42 AM
bwkaz: the keyword is 'synchronized', but you were close ;) And IMO, you don't need to constantly read a second array - if you know how many threads you'll have (which it appears you're supposing), then just check the String array - if the value is 'null', then your thread hasn't finished.

bwkaz
06-06-2003, 06:46 PM
Oh... duh!

Yep, you don't need the second array at all. As long as none of the threads can return null, of course -- whatever you initialize the first array's elements to, make sure it's out-of-band for the thread (make sure the thread will never write it into that array).