views:

48

answers:

5

In Java, I want to download some data asynchronously in a Thread (or Runnable) object, and have the Thread put it's data into an Object I've declared within my main Thread.

How could I do this please?

A: 

You can pass the Object to the constructor of the download thread. Just make sure it is thread safe...

Maurice Perry
+1  A: 
  1. Pass that object (collection?) to each thread (preferred)
  2. Declare it a static member and access it statically.

Either way you would need to synchronize the "putting". Or, if it is a collection, use its java.util.concurrent equivalent (if exists)

If you don't want to paralelize the download, but simply start it in another thread, you may want Callable instead of Runnable

Bozho
+3  A: 

It would be better to use a FutureTask - having a separate thread put data into the main thread's object is prone to synchronization errors.

Michael Borgwardt
A: 

You need to pass the object into the Thread's constructor and assign it to a field. This, of course, leads to synchronization problems as that object will be "touched" by both threads so you need to use an appropriate protection scheme.

Itay
A: 

This depends on your synchronization needs. Do you need to modify the objects from both threads or is it read only from the main thread? Anyway the simplest method will be to use synchronized code:

Main thread:

public setObject(Object obj) {
  synchronized(this) {
        this.obj = obj;
    }
}

Call the above method from the second thread. You could also use LockObjects.

Have also a look at the Exchanger class.

kgiannakakis