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?
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.
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
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.