I am slightly ashamed to ask this basic question, but here it is.
Let's say I have a main class and a worker thread. The worker thread does some asynchronous work and shall return the results to a callback of the main class.
Now what I am struggling with is: the callback of the main class is executed as part of the worker thread. I have done this a dozen times and it never caused any issues for me, but I am wondering how to elegantly pass back a response from the worker thread to the actual main thread.
I know I can use Future
and FutureTask
etc., but it feels clunky to me.
Example:
class ThreadTest {
private Runnable mRunnable;
public ThreadTest() {
System.out.println("ThreadTest(): thread " + Thread.currentThread().getId());
mRunnable = new Runnable() {
public void run() {
System.out.println("run(): thread " + Thread.currentThread().getId());
print();
}
};
new Thread(mRunnable).start();
}
private void print() {
System.out.println("print(): thread " + Thread.currentThread().getId());
}
public static void main(String... args) {
System.out.println("main(): thread " + Thread.currentThread().getId());
ThreadTest t = new ThreadTest();
}
}
Output:
main(): thread 1
ThreadTest(): thread 1
run(): thread 9
print(): thread 9
What I would like to get:
main(): thread 1
ThreadTest(): thread 1
run(): thread 9
print(): thread 1