在java的runnable中调用runnable会发生什么?

klr1opcd  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(243)

这个问题在这里已经有答案了

如果我们直接调用run方法会发生什么(2个答案)
上个月关门了。
我上了一节课:

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
        }
    }
}

RunnableImplA & runnableB 在同一个线程上运行?

jhdbpxl9

jhdbpxl91#

为了创建新线程,您需要调用 start() 方法 Thread 类,它在内部调用 run() 方法。因为在这里我们不使用start方法调用它,所以它和对对象的任何其他方法调用一样。所以是的,它将在同一个线程中。
如果您想在不同的线程中运行它,那么 run() 方法需要更新如下:

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

gt0wga4j2#

runnable.run()不创建线程。这只是一个简单的函数调用,没有什么特别的事情发生。所以,是的,同样的线索。

smdncfj3

smdncfj33#

是的,它在同一个线程中运行。
runnable只是一个接口,其他什么都不是。像thread这样的类可以接受runnable作为参数。

相关问题