0

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?

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
  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

Comments

0

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.