Why can't we call Thread#sleep() directly inside a Lambda function? Why can't we call Thread#sleep() directly inside a Lambda function? multithreading multithreading

Why can't we call Thread#sleep() directly inside a Lambda function?


Thread.sleep is a static method in the Thread class.

The reason you can call sleep directly without any qualifiers in an anonymous class is because you are actually in the context of a class that inherits from Thread. Therefore, sleep is accessible there.

But in the lambda case, you are not in a class that inherits from Thread. You are inside whatever class is surrounding that code. Therefore, sleep can't be called directly and you need to say Thread.sleep. The documentation also supports this:

Lambda expressions are lexically scoped. This means that they do not inherit any names from a supertype or introduce a new level of scoping. Declarations in a lambda expression are interpreted just as they are in the enclosing environment.

Basically that is saying that inside the lambda, you are actually in the same scope as if you were outside of the lambda. If you can't access sleep outside the lambda, you can't on the inside either.

Also, note that the two ways of creating a thread that you have shown here is intrinsically different. In the lambda one, you are passing a Runnable to the Thread constructor, whereas in the anonymous class one, you are creating a Thread by creating an anonymous class of it directly.


In the first approach, you are passing a Runnable to the Thread, you need call Thread.sleep:

Thread t2 = new Thread(() -> {    try {        Thread.sleep(1000);    } catch (InterruptedException e) {    }});

it is the short version of:

Runnable runnable = new Runnable() {    public void run(){        try {            Thread.sleep(1000);        } catch (InterruptedException e) {}    }};Thread t2 = new Thread(runnable);

While in the second, you are overriding thread.run method directly, so it's ok to call thread.sleep in thread.run.


This ends up being a misunderstanding of Scope.

When you are passing in a lambda to the thread, you are not creating a subclass of Thread, instead you are passing in the FunctionalInterface of Runnable and calling a constructor of Thread. When you attempt to call Sleep, the context of your scope is a combination of Runnable + your class (you can call default methods if the Runnable interface had them), not Thread.

Runnable does not have sleep() defined, but Thread does.

When you create an anonymous inner class, you are subclassing Thread, so sleep() is available for you to call, as the context of the Scope is a subclass of Thread.

Calling static methods, without the class name is discouraged for exactly this kind of misunderstanding. Using Thread.Sleep is both correct, and unambiguous in all circumstances.