Tim
Tim

Reputation: 31

Java thread, accessing object in main code

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

Answers (5)

Bozho
Bozho

Reputation: 597116

  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

Upvotes: 1

kgiannakakis
kgiannakakis

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

Itay Maman
Itay Maman

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

Michael Borgwardt
Michael Borgwardt

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

Maurice Perry
Maurice Perry

Reputation: 32831

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

Upvotes: 0

Related Questions