简体   繁体   中英

Inner class runnable in java

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?

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM