3
votes

say I have a class called "Example"

inside "Example" I have an inner class which is a runnable

I execute the runnable inside "Example"

public class Example {
    public Example() {
       //executing the runnable here
    }

    private void a() {
    }
    public void b() {
    }

    public class RunMe implements Runnable {

       public void run() {
           a();
           b();
       }

    }
}

what happens here assuming that Example runs on the main thread?

does a and b run from the RunMe thread or the main thread?

does it matter that a is private and b is public?

3
I can see no Thread in your code: assuming you create as a filed of Example, pass the runnable to the Thread and execute it the Runme is executed in the thread, can see a and b as it is an inner class no matter modifiers. - ilmirons
yeah, I meant executing the runnable in a thread in the constructor of Example, so you mean to say that both of Example's methods will be run on the thread and not on main thread? - Amir.F

3 Answers

5
votes

You missed out the key piece of code to enable us to answer your question - the constructor.

If your constructor looks like this:

public Example() {
    (new Thread(new RunMe())).start();
}

Then a() and b() will run on the thread you just created (the "RunMe" thread as you call it).

However, if your constructor looks like this:

public Example() {
    (new RunMe()).run();
}

Then you're not actually running it on another thread (you're just calling a method in another class, it just happens to be called 'run'), and so a() and b() will run on the 'main' thread.

The private/public thing is irrelevant here because RunMe is an inner class so can access even private methods of Example.

0
votes

If your Example constructor has in it

new Thread(new RunMe()).start()

then a() and b() will run on that thread.

However, they may run before the constructor has finished executing, so their behaviour will be undefined.

0
votes

Inner class are just some magic kind of extracted/transformed.

public static class Example$RunMe implements Runnable {

   // Autocode
   private final Example $this;
   public RunMe(Example _this){
       $this=_this;
   }

   public void run() {
       $this.a(); // even if private
       $this.b();
   }

}

So the thread you are calling run is the Thread a() and b() are called, it makes no difference if they are public or private.