Search code examples
javamultithreadingobserver-pattern

Threading and observer pattern in Java


Suppose I have two classes, Main class and Worker class

class Main implements StateChangeListener extends JFrmame{

   public void notifyMe(State state){
        //Change the GUI according to the state
   }  
}


class Worker extends Thread{
    public StateChangeListener listener;
    public void run(){
        listener.notifyMe(state);
    }
}

My question is: Suppose worker is run in another thread, which thread will run the function notifyMe()?
The Main thread or the worker thread? Thank You


Solution

  • A function call is executed under the control of a thread who called it. In your case since you are calling notifyMe() from the worker thread, the worker thread will be responsible for executing the method notifyMe().

    You can test this using Thread.currentThread().getName() to print the name of the Thread. See the getter/ setter for Thread name at this link.