Hi Folks,

I have a general question about multithreading...

I have a small app that is multithreaded. I have a main() class and a separate Runnable class that implements the Runnable interface. The problem I have is that the Runnable class needs to return an integer to main(). But this isn't possible because the run() method in my Runnable class is of type void, so no value can be returned.

I suppose I could move the code that returns a value to a new class that is not Runnable but is called inside the run() method, but I think that still leaves me with the same basic problem.

Is there a general approach or widely accepted practice to this problem? Just looking for a little guidance on how one should tackle this sort of problem.

Many Thanks!

Tyster

If you are able to detail what exactly are you trying to do by attempting to return the integer I think we could be of more use to you.

Take a look at the Callable interface, which can return a value and throw Exceptions.

Maybe this will help...

My main method is required to read filenames as command line arguments, such as

java MyApp textfile1. txt textfile2.txt textfile3.txt

The app is supposed to use a separate thread to count the number of words in each text file. So, since a new thread is required for reading each text file, I have a separate class that implements the Runnable interface and does the actual counting of words. So I have...

public class CountWords implements Runnable {

...  instance variables and constructor ...  then the run() method...

     public void run() {

	> Word counting logic <

	}
	return numWords;

And this is where the trouble starts... I can't return the number of words counted because the run() method is a void method.

I was thinking that perhaps I could do the word counting in main() instead, but then its not clear to me how I would use a new thread for counting the words in each file. I mean, what would be the purpose of my Runnable class at that point?

Andy advice is greatly appreciated!

Tyster

I think I'll try using Callable instead of Runnable.

Many Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.