Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The question is confusing, but thats what i want to do:

public class Main
{
    MyClass instance = new MyClass();
    Thread secondThread = new Thread(instance);

    public static void main()
    {
         secondThread.start();
         //here i want to call foo(), but be processed by secondThread thread(not the Main thread)
    }
}


public class MyClass implements Runnable
{
    @Override
    public void run()
    {

    }

    public void foo()
    {
        System.out.println("foo");
    }
}

If i use "instance.foo();" it will be processed by the Main thread.

like image 626
Cássio Eudardo Avatar asked Nov 04 '11 16:11

Cássio Eudardo


3 Answers

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().

like image 112
Chris Hannon Avatar answered Oct 10 '22 13:10

Chris Hannon


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().

like image 34
Martin James Avatar answered Oct 10 '22 14:10

Martin James


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");
    }
}
like image 1
codefarmer Avatar answered Oct 10 '22 14:10

codefarmer