Calling a method from the class that created a thread, in the thread

Viewed 53

I have a method that I want to call in RunnerClass, in a non-static way in ThreadClass.

public class CallingClass{
    CallingClass(){
        ClassTwo thread = new ClassTwo();
        thread.start();
    }

    public void someMethod(){}

}

public class ThreadClass extends Thread{
    public void run(){
        //Some thread logic
        CallingClass.someMethod();
    }
}

Obviously this won't work. The method is not static (and I'm not allowed to make it static), but in the above example I'm trying to access it in a static way, if only because I feel it best represents what I would like to do.
If it makes sense, I would like for the thread to be able to notify the instance of CallingClass that it needs to call someMethod()

Is there a neat way to do this?

2 Answers

You could use ThreadClass as an inner class of CallingClass and call the mothod directly.

 public class CallingClass{
    CallingClass(){
        ClassTwo thread = new ClassTwo();
        thread.start();
    }

    public void someMethod(){}

    public class ThreadClass extends Thread{
    public void run(){
        //Some thread logic
        someMethod();
    }

}

}

What about creating ClassTwo constructer that gets a parameter with CallingClass type?

public class ThreadClass extends Thread{
    CallingClass callingClass;

    public ThreadClass(CallingClass callingClass) {
            this.callingClass = callingClass;
    }
    public void run(){
        //Some thread logic
        callingClass.someMethod();
    }
}

And create ClassTwo like this:

public class CallingClass{
    CallingClass(){
        ClassTwo thread = new ClassTwo(this);
        thread.start();
    }

    public void someMethod(){}

}
Related