2 Threads issues. How to return data from a thread located in other class

Advertisement

2 Threads issues. How to return data from a thread located in other class
I have 2 questions.
This is the context. From main I start one thread that does a little job then starts another thread and waits for it to end to continue.
1) The last started thread needs to return a string to the Thread started from main. How can I accomplish that, because I read that I cannot use
synchronized methods outside different classes (and the threads belongs to different classes).
2) From the main thread I start the Second Thread located in another class like this ClassName obj = new ClassName(arg); obj.start(); obj.join()
Is that correct for waiting for the created thread to finish ?
Repaly
1) The last started thread needs to return a string to the Thread started from main. How can I accomplish that, because I read that I cannot use
synchronized methods outside different classes (and the threads belongs to different classes).Threads do not "belong" to classes. Class code executes in a particular thread. The class instances exist as long as something, somewhere, holds a strong reference to them.
So when you start a new thread, hold a strong reference to the object being executed by that thread. When the thread is done, retrieve your data from that object.
Even better, don't subclass Thread to create your objects. Instead, implement Callable, and use a ThreadPoolExecutor to execute it.
Read More: The other 7 answers