Call method of a runnable instance outside the runnable that is executed by the runnable's thread Call method of a runnable instance outside the runnable that is executed by the runnable's thread multithreading multithreading

Call method of a runnable instance outside the runnable that is executed by the runnable's thread


The idea of a Runnable is that it's a consolidated piece of code that can be executed by something else inside of whatever context it chooses (in this case, a thread). The second thread will call the run() method when it starts, so you may want to have a call to foo() within your MyClass.run() method. You cannot arbitrarily decide, from the main thread, that the second thread is now going to abandon whatever it was doing in the run() method and start working on foo().


You cannot call a thread, you can only signal it. If you want foo() to be executed, you have to signal run() to ask it to execute foo().


change your code as below:

public class Main{    Object signal = new Object();    MyClass instance = new MyClass();    Thread secondThread = new Thread(instance);    public static void main()    {         instance.setSignal(signal);         secondThread.start();          synchronize(signal)          {          try{          signal.notify();**//here will notify the secondThread to invoke the foo()**         }         catch(InterrupedException e)         {                e.printStackTrace();          }    }}public class MyClass implements Runnable{    Object signal;    public setSignal(Object sig)    {        signal = sig;    }    @Override    public void run()    {       synchronize(signal)       {          try{          signal.wait();         }         catch(InterrupedException e)         {                e.printStackTrace();          }       }        this.foo();    }    public void foo()    {        System.out.println("foo");    }}