Possible duplicate: need-help-returning-object-in-thread-run-method
Hello. I have a class implementing runnable and I have a List, storing Threads instantiated with
I had the same problem. Here is my solution:
public static class TestRunnable implements Runnable {
public String foo = "hello";
public void run() {
foo = "world";
}
public static void main(String[] args) {
TestRunnable runobject = new TestRunnable();
Thread t = new Thread(runobject);
runobject.foo; //The variable from runnable. hello;
t.start();
runobject.foo; //The variable from runnable. world;
}
To give a concrete example of Paul Crowley's solution, I think this is what he suggests:
public class BackgroundJob<JOB extends Runnable> extends Thread {
private final JOB mJob;
public BackgroundJob(JOB job) {
super(job);
mJob = job;
}
public JOB getJob() {
return mJob;
}
}
This is how you could implement this directly.
public static void main(String[] args) {
// Keep a reference to the runnable object for later ...
TestRunnable r = new TestRunnable();
Thread t = new Thread(r);
t.start();
// Wait until the child thread has finished
t.join();
// Pull the result out of the runnable.
System.out.println(r.foo);
}
However, the modern (less error prone) way to do this kind of thing is to use the higher-level concurrency classes in java.util.concurrent.
I think, if you can, it is to revert the situation. Then in this case a good solution is to store the thread in your runnable class. And your runnable has a start() function that launch and start itself the local thread and call thread.start. Like this you can have a list of your threaded objects. Also you can have an accessor to get the thread.
public class Threaded extends other implements Runnable {
Thread localThread;
@Override
public void run() {
//...
}
public void start() {
localThread = new Thread(this);
localThread.start();
}
}
TestRunnable r = new TestRunnable();
Thread t = new Thread(r);
t.start();
//there you need to wait until thread is finished, or just a simple Thread.sleep(1000); at this case
System.out.println(r.foo);
BTW, in real case you need to use Callable and FutureTask