Search code examples
javarunnable

What's happen when call a Runnable in a runnable in Java?


I got a class:

public class RunnableImplA implements Runnable {


    private Runnable runnableB;
    
    public RunnableImplA(Runnable runnableB) {
        super();
        runnableB= runnableB;
    }


    @Override
    public void run() {
        try {
        
            runnableB.run();
        } finally {
            // some code
        }
    }
}

Do RunnableImplA & runnableB run on same Thread?


Solution

  • In order to create new Thread you need to call start() method of Thread class, which internally calls the run() method. As here we don't call it with start method, it is just like any other method call on object. So yes, it will be in same Thread.

    If you want to run it in different thread, then run() method needs to be updated as below:

    @Override
        public void run() {
            try {
                Thread innerThread = new Thread(runnableB);
                innerThread.start();
            } finally {
                // some code
            }
        }