Reputation: 7604
I have a class from which I am calling a new thread.
public class MainClass{
private void cleardata() {
// do something on a separate thread
new Thread(new Runnable() {
@Override
public void run() {
//Do Something
//After this I would like to notify my MainClass that some thing has been done and pass a value.
}
}
}
private void callbackFunc(int a){
// Do something based on value of a
}
}
I have a function in my MainClass. But how do i call this function from my new thread, so as to receive a callback. Thanks.
Upvotes: 2
Views: 159
Reputation: 122364
You should just be able to call the method in MainClass
by its name just as if you were calling from directly inside MainClass
itself (as opposed to from the inner class).
If a method name you want to call happens to conflict with one that your inner class has inherited from Object
then you can prefix the call with MainClass.this
, e.g. MainClass.this.toString()
calls toString
on MainClass
, whereas just toString()
calls it on the inner class instance.
Upvotes: 1
Reputation: 28951
Just do it:
public class MainClass{
private void cleardata() {
// do something on a separate thread
new Thread(new Runnable() {
@Override
public void run() {
//Do Something
notifyTheClass("a parameter");
}
}
private void notifyTheClass(String aParam) {
//..do something else
}
}
}
But it is not related to threads, this is about inner classes. If you want the main thread to wait until the new thread is finishes, use Futures for a result. Or use some other multithreading primitives.
Upvotes: 0
Reputation: 21883
public class MainClass{
private void cleardata() {
// do something on a separate thread
new Thread(new Runnable() {
@Override
public void run() {
callBackFunc(result);
}
}
}
private void callBackFunc(int a) {
}
}
Upvotes: 0
Reputation: 4202
In such a case pass the instance of MainClass to the thread class ((during creation)) so that it can call method on it. Having inner class as suggested by others is also a good option.
Something similar-
class MainClass {
private void cleardata() {
new Thread(new MyThread(this)).start();
}
}
class MyThread implements Runnable {
private MainClass mc;
MyThread(MainClass mc) {
this.mc = mc;
}
public void run() {
// do something
// mc.someMethod();
}
}
Upvotes: 0