Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
Amir.F Avatar asked Oct 14 '25 14:10

Amir.F


1 Answers

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.

like image 199
stripybadger Avatar answered Oct 17 '25 04:10

stripybadger