thread returning an object?

R

R

Hello everybody.

As a newbie I have a very simple question.

Can a thread return a non void value? (run method is void...)

e.g. an Object (LinedList, String[][]) ?

thanks in advance for Your help
best regards
R
 
E

Eric Sosman

R said:
Hello everybody.

As a newbie I have a very simple question.

Can a thread return a non void value? (run method is void...)

e.g. an Object (LinedList, String[][]) ?

The run() method is void, and cannot return anything.
Even if it could, how would the caller know what to do
with it? Note that the caller of run() is not your code,
but something inside the JVM.

All is not lost, though. Remember, you get to write
the class that implements Runnable or extends Thread, and
you can endow this class with any methods and fields you
choose. Furthermore, objects of your class will not vanish
simply because their threads finish executing; they're just
like any other objects and will continue to exist as long
as you have references to them. So if your object computes
a "final answer," you can call your object's methods to
retrieve that answer after the thread finishes. Provided
you synchronize properly, you can even retrieve "preliminary
answers" while the thread is still running.
 
N

Nigel Wade

R said:
Hello everybody.

As a newbie I have a very simple question.

Can a thread return a non void value? (run method is void...)

e.g. an Object (LinedList, String[][]) ?

thanks in advance for Your help
best regards
R

Have a look at the implementation of SwingWorker at
http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/SwingWorker.java.

I think this will show you how to do what you require. The getValue() and
get() methods return an Object which is calculated by the SwingWorker
thread.
 
B

ByteCoder

Hello everybody.

As a newbie I have a very simple question.

Can a thread return a non void value? (run method is void...)

e.g. an Object (LinedList, String[][]) ?

thanks in advance for Your help
best regards
R

You could let the Thread starting class implement an interface and when
the thread is finished executing it would call the synchronized
protected/public method with the object you want the thread to return.
The thread starting class would do something with the object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top