Reputation: 31
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?
Upvotes: 0
Views: 617
Reputation: 597116
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
Upvotes: 1
Reputation: 104178
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.
Upvotes: 0
Reputation: 30723
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.
Upvotes: 0
Reputation: 346317
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.
Upvotes: 3
Reputation: 32831
You can pass the Object to the constructor of the download thread. Just make sure it is thread safe...
Upvotes: 0