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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
11
down vote

favorite












The below code is giving me compile time error:



The method sleep(int) is undefined for the type A (A is my class name).



 Thread t2 = new Thread(() -> 
try
sleep(1000);

catch (InterruptedException e)
);


Whereas, when I specify using Anonymous inner class, there is no compile time error:



 Thread t1 = new Thread()
public void run()
try
sleep(1000);
catch (InterruptedException e)

;


The below code also works fine:



Thread t3 = new Thread(() -> System.out.println("In lambda"));


How things work inside a lamda expression body? Please, help.



From many answers, I can see that the error can be resolved using Thread.sleep(1000) in my first approach. However, I'd really appreciate if someone could explain me how scope/context works in a lambda expression.










share|improve this question



















  • 2




    What is the compiler error you are getting?
    – Ryan The Leach
    1 hour ago










  • @RyanTheLeach, The method sleep(int) is undefined for the type A, Here A is my class Name.
    – ChandraBhan Singh
    58 mins ago










  • have you tried to import static java.lang.Thread.sleep;
    – vmrvictor
    55 mins ago










  • @Chandra, I've edited my answer in order to answer your new question. I hope it is of help. Cheers!
    – Talendar
    19 mins ago














up vote
11
down vote

favorite












The below code is giving me compile time error:



The method sleep(int) is undefined for the type A (A is my class name).



 Thread t2 = new Thread(() -> 
try
sleep(1000);

catch (InterruptedException e)
);


Whereas, when I specify using Anonymous inner class, there is no compile time error:



 Thread t1 = new Thread()
public void run()
try
sleep(1000);
catch (InterruptedException e)

;


The below code also works fine:



Thread t3 = new Thread(() -> System.out.println("In lambda"));


How things work inside a lamda expression body? Please, help.



From many answers, I can see that the error can be resolved using Thread.sleep(1000) in my first approach. However, I'd really appreciate if someone could explain me how scope/context works in a lambda expression.










share|improve this question



















  • 2




    What is the compiler error you are getting?
    – Ryan The Leach
    1 hour ago










  • @RyanTheLeach, The method sleep(int) is undefined for the type A, Here A is my class Name.
    – ChandraBhan Singh
    58 mins ago










  • have you tried to import static java.lang.Thread.sleep;
    – vmrvictor
    55 mins ago










  • @Chandra, I've edited my answer in order to answer your new question. I hope it is of help. Cheers!
    – Talendar
    19 mins ago












up vote
11
down vote

favorite









up vote
11
down vote

favorite











The below code is giving me compile time error:



The method sleep(int) is undefined for the type A (A is my class name).



 Thread t2 = new Thread(() -> 
try
sleep(1000);

catch (InterruptedException e)
);


Whereas, when I specify using Anonymous inner class, there is no compile time error:



 Thread t1 = new Thread()
public void run()
try
sleep(1000);
catch (InterruptedException e)

;


The below code also works fine:



Thread t3 = new Thread(() -> System.out.println("In lambda"));


How things work inside a lamda expression body? Please, help.



From many answers, I can see that the error can be resolved using Thread.sleep(1000) in my first approach. However, I'd really appreciate if someone could explain me how scope/context works in a lambda expression.










share|improve this question















The below code is giving me compile time error:



The method sleep(int) is undefined for the type A (A is my class name).



 Thread t2 = new Thread(() -> 
try
sleep(1000);

catch (InterruptedException e)
);


Whereas, when I specify using Anonymous inner class, there is no compile time error:



 Thread t1 = new Thread()
public void run()
try
sleep(1000);
catch (InterruptedException e)

;


The below code also works fine:



Thread t3 = new Thread(() -> System.out.println("In lambda"));


How things work inside a lamda expression body? Please, help.



From many answers, I can see that the error can be resolved using Thread.sleep(1000) in my first approach. However, I'd really appreciate if someone could explain me how scope/context works in a lambda expression.







java multithreading lambda java-8






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 15 mins ago









Talendar

602215




602215










asked 1 hour ago









ChandraBhan Singh

9521118




9521118







  • 2




    What is the compiler error you are getting?
    – Ryan The Leach
    1 hour ago










  • @RyanTheLeach, The method sleep(int) is undefined for the type A, Here A is my class Name.
    – ChandraBhan Singh
    58 mins ago










  • have you tried to import static java.lang.Thread.sleep;
    – vmrvictor
    55 mins ago










  • @Chandra, I've edited my answer in order to answer your new question. I hope it is of help. Cheers!
    – Talendar
    19 mins ago












  • 2




    What is the compiler error you are getting?
    – Ryan The Leach
    1 hour ago










  • @RyanTheLeach, The method sleep(int) is undefined for the type A, Here A is my class Name.
    – ChandraBhan Singh
    58 mins ago










  • have you tried to import static java.lang.Thread.sleep;
    – vmrvictor
    55 mins ago










  • @Chandra, I've edited my answer in order to answer your new question. I hope it is of help. Cheers!
    – Talendar
    19 mins ago







2




2




What is the compiler error you are getting?
– Ryan The Leach
1 hour ago




What is the compiler error you are getting?
– Ryan The Leach
1 hour ago












@RyanTheLeach, The method sleep(int) is undefined for the type A, Here A is my class Name.
– ChandraBhan Singh
58 mins ago




@RyanTheLeach, The method sleep(int) is undefined for the type A, Here A is my class Name.
– ChandraBhan Singh
58 mins ago












have you tried to import static java.lang.Thread.sleep;
– vmrvictor
55 mins ago




have you tried to import static java.lang.Thread.sleep;
– vmrvictor
55 mins ago












@Chandra, I've edited my answer in order to answer your new question. I hope it is of help. Cheers!
– Talendar
19 mins ago




@Chandra, I've edited my answer in order to answer your new question. I hope it is of help. Cheers!
– Talendar
19 mins ago












6 Answers
6






active

oldest

votes

















up vote
3
down vote



accepted










Your doubt is generated by a misunderstanding about how the scopes of a lambda expression and an anonymous class work. Below, I will try to clarify this.



Lambda expressions DO NOT introduce a new level of scoping. This means that, inside it, you can only access the same things that you would be able to access in the immediately enclosing code block. See what the docs say:




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.




Anonymous classes work differently. They do introduce a new level of scoping. They behave much like a local class (a class that you declare inside a block of code), although they can't have constructors. See what the docs say:




Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:



  • An anonymous class has access to the members of its enclosing class.

  • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

  • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing
    scope that have the same name. See Shadowing for more information.



In this context, I can now answer your question. The anonymous class will act like a local class inside Thread and, thus, it will be able to access sleep() directly, since it will be within it's scope. However, in the lambda expression, sleep() isn't available within it's scope (you wouldn't be able to call sleep() directly on the line before the lambda, for example), so that you must use Thread.sleep().






share|improve this answer





























    up vote
    8
    down vote













    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.






    share|improve this answer


















    • 1




      The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
      – LuCio
      46 mins ago











    • @LuCio Thanks! edited that into the answer.
      – Sweeper
      41 mins ago










    • You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
      – Holger
      33 mins ago

















    up vote
    2
    down vote













    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.






    share|improve this answer



























      up vote
      2
      down vote













      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 class 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.






      share|improve this answer





























        up vote
        1
        down vote













        Following code works:



         Thread t2 = new Thread(() -> 
        try
        Thread.sleep(1000);

        catch (InterruptedException e)
        );


        This is because sleep(int milliseconds) is a method from Thread class while you are creating and passing a Runnable instance to Thread class constructor.



        In the second method, You are creating an anonymous inner class instance of Thread class and thus have access to all Thread class methods.






        share|improve this answer



























          up vote
          0
          down vote













          Thread.sleep is static method ...



           Thread t2 = new Thread(() -> 
          try
          Thread.sleep(1000);

          catch (InterruptedException e)
          );





          share|improve this answer




















          • that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
            – Carlos Heuberger
            15 mins ago











          Your Answer





          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52602990%2fwhy-cant-we-call-threadsleep-directly-inside-a-lambda-function%23new-answer', 'question_page');

          );

          Post as a guest






























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote



          accepted










          Your doubt is generated by a misunderstanding about how the scopes of a lambda expression and an anonymous class work. Below, I will try to clarify this.



          Lambda expressions DO NOT introduce a new level of scoping. This means that, inside it, you can only access the same things that you would be able to access in the immediately enclosing code block. See what the docs say:




          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.




          Anonymous classes work differently. They do introduce a new level of scoping. They behave much like a local class (a class that you declare inside a block of code), although they can't have constructors. See what the docs say:




          Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:



          • An anonymous class has access to the members of its enclosing class.

          • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

          • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing
            scope that have the same name. See Shadowing for more information.



          In this context, I can now answer your question. The anonymous class will act like a local class inside Thread and, thus, it will be able to access sleep() directly, since it will be within it's scope. However, in the lambda expression, sleep() isn't available within it's scope (you wouldn't be able to call sleep() directly on the line before the lambda, for example), so that you must use Thread.sleep().






          share|improve this answer


























            up vote
            3
            down vote



            accepted










            Your doubt is generated by a misunderstanding about how the scopes of a lambda expression and an anonymous class work. Below, I will try to clarify this.



            Lambda expressions DO NOT introduce a new level of scoping. This means that, inside it, you can only access the same things that you would be able to access in the immediately enclosing code block. See what the docs say:




            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.




            Anonymous classes work differently. They do introduce a new level of scoping. They behave much like a local class (a class that you declare inside a block of code), although they can't have constructors. See what the docs say:




            Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:



            • An anonymous class has access to the members of its enclosing class.

            • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

            • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing
              scope that have the same name. See Shadowing for more information.



            In this context, I can now answer your question. The anonymous class will act like a local class inside Thread and, thus, it will be able to access sleep() directly, since it will be within it's scope. However, in the lambda expression, sleep() isn't available within it's scope (you wouldn't be able to call sleep() directly on the line before the lambda, for example), so that you must use Thread.sleep().






            share|improve this answer
























              up vote
              3
              down vote



              accepted







              up vote
              3
              down vote



              accepted






              Your doubt is generated by a misunderstanding about how the scopes of a lambda expression and an anonymous class work. Below, I will try to clarify this.



              Lambda expressions DO NOT introduce a new level of scoping. This means that, inside it, you can only access the same things that you would be able to access in the immediately enclosing code block. See what the docs say:




              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.




              Anonymous classes work differently. They do introduce a new level of scoping. They behave much like a local class (a class that you declare inside a block of code), although they can't have constructors. See what the docs say:




              Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:



              • An anonymous class has access to the members of its enclosing class.

              • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

              • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing
                scope that have the same name. See Shadowing for more information.



              In this context, I can now answer your question. The anonymous class will act like a local class inside Thread and, thus, it will be able to access sleep() directly, since it will be within it's scope. However, in the lambda expression, sleep() isn't available within it's scope (you wouldn't be able to call sleep() directly on the line before the lambda, for example), so that you must use Thread.sleep().






              share|improve this answer














              Your doubt is generated by a misunderstanding about how the scopes of a lambda expression and an anonymous class work. Below, I will try to clarify this.



              Lambda expressions DO NOT introduce a new level of scoping. This means that, inside it, you can only access the same things that you would be able to access in the immediately enclosing code block. See what the docs say:




              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.




              Anonymous classes work differently. They do introduce a new level of scoping. They behave much like a local class (a class that you declare inside a block of code), although they can't have constructors. See what the docs say:




              Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:



              • An anonymous class has access to the members of its enclosing class.

              • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

              • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing
                scope that have the same name. See Shadowing for more information.



              In this context, I can now answer your question. The anonymous class will act like a local class inside Thread and, thus, it will be able to access sleep() directly, since it will be within it's scope. However, in the lambda expression, sleep() isn't available within it's scope (you wouldn't be able to call sleep() directly on the line before the lambda, for example), so that you must use Thread.sleep().







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 13 mins ago

























              answered 55 mins ago









              Talendar

              602215




              602215






















                  up vote
                  8
                  down vote













                  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.






                  share|improve this answer


















                  • 1




                    The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
                    – LuCio
                    46 mins ago











                  • @LuCio Thanks! edited that into the answer.
                    – Sweeper
                    41 mins ago










                  • You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
                    – Holger
                    33 mins ago














                  up vote
                  8
                  down vote













                  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.






                  share|improve this answer


















                  • 1




                    The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
                    – LuCio
                    46 mins ago











                  • @LuCio Thanks! edited that into the answer.
                    – Sweeper
                    41 mins ago










                  • You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
                    – Holger
                    33 mins ago












                  up vote
                  8
                  down vote










                  up vote
                  8
                  down vote









                  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.






                  share|improve this answer














                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 41 mins ago

























                  answered 53 mins ago









                  Sweeper

                  56.7k962124




                  56.7k962124







                  • 1




                    The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
                    – LuCio
                    46 mins ago











                  • @LuCio Thanks! edited that into the answer.
                    – Sweeper
                    41 mins ago










                  • You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
                    – Holger
                    33 mins ago












                  • 1




                    The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
                    – LuCio
                    46 mins ago











                  • @LuCio Thanks! edited that into the answer.
                    – Sweeper
                    41 mins ago










                  • You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
                    – Holger
                    33 mins ago







                  1




                  1




                  The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
                  – LuCio
                  46 mins ago





                  The documentation says: the lambda expression does not introduce a new level of scoping. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
                  – LuCio
                  46 mins ago













                  @LuCio Thanks! edited that into the answer.
                  – Sweeper
                  41 mins ago




                  @LuCio Thanks! edited that into the answer.
                  – Sweeper
                  41 mins ago












                  You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
                  – Holger
                  33 mins ago




                  You can still use import static java.lang.Thread.sleep;. But having to catch InterruptedException creates far more visual noise than a preceding Thread.. So, to create a new thread which just sleeps one second, I’d use new Thread(() -> LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1))) instead.
                  – Holger
                  33 mins ago










                  up vote
                  2
                  down vote













                  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.






                  share|improve this answer
























                    up vote
                    2
                    down vote













                    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.






                    share|improve this answer






















                      up vote
                      2
                      down vote










                      up vote
                      2
                      down vote









                      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.






                      share|improve this answer












                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 58 mins ago









                      Sun

                      14.2k31541




                      14.2k31541




















                          up vote
                          2
                          down vote













                          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 class 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.






                          share|improve this answer


























                            up vote
                            2
                            down vote













                            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 class 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.






                            share|improve this answer
























                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              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 class 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.






                              share|improve this answer














                              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 class 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.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 15 mins ago

























                              answered 54 mins ago









                              Ryan The Leach

                              2,33411736




                              2,33411736




















                                  up vote
                                  1
                                  down vote













                                  Following code works:



                                   Thread t2 = new Thread(() -> 
                                  try
                                  Thread.sleep(1000);

                                  catch (InterruptedException e)
                                  );


                                  This is because sleep(int milliseconds) is a method from Thread class while you are creating and passing a Runnable instance to Thread class constructor.



                                  In the second method, You are creating an anonymous inner class instance of Thread class and thus have access to all Thread class methods.






                                  share|improve this answer
























                                    up vote
                                    1
                                    down vote













                                    Following code works:



                                     Thread t2 = new Thread(() -> 
                                    try
                                    Thread.sleep(1000);

                                    catch (InterruptedException e)
                                    );


                                    This is because sleep(int milliseconds) is a method from Thread class while you are creating and passing a Runnable instance to Thread class constructor.



                                    In the second method, You are creating an anonymous inner class instance of Thread class and thus have access to all Thread class methods.






                                    share|improve this answer






















                                      up vote
                                      1
                                      down vote










                                      up vote
                                      1
                                      down vote









                                      Following code works:



                                       Thread t2 = new Thread(() -> 
                                      try
                                      Thread.sleep(1000);

                                      catch (InterruptedException e)
                                      );


                                      This is because sleep(int milliseconds) is a method from Thread class while you are creating and passing a Runnable instance to Thread class constructor.



                                      In the second method, You are creating an anonymous inner class instance of Thread class and thus have access to all Thread class methods.






                                      share|improve this answer












                                      Following code works:



                                       Thread t2 = new Thread(() -> 
                                      try
                                      Thread.sleep(1000);

                                      catch (InterruptedException e)
                                      );


                                      This is because sleep(int milliseconds) is a method from Thread class while you are creating and passing a Runnable instance to Thread class constructor.



                                      In the second method, You are creating an anonymous inner class instance of Thread class and thus have access to all Thread class methods.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 54 mins ago









                                      S.K.

                                      1,853717




                                      1,853717




















                                          up vote
                                          0
                                          down vote













                                          Thread.sleep is static method ...



                                           Thread t2 = new Thread(() -> 
                                          try
                                          Thread.sleep(1000);

                                          catch (InterruptedException e)
                                          );





                                          share|improve this answer




















                                          • that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
                                            – Carlos Heuberger
                                            15 mins ago















                                          up vote
                                          0
                                          down vote













                                          Thread.sleep is static method ...



                                           Thread t2 = new Thread(() -> 
                                          try
                                          Thread.sleep(1000);

                                          catch (InterruptedException e)
                                          );





                                          share|improve this answer




















                                          • that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
                                            – Carlos Heuberger
                                            15 mins ago













                                          up vote
                                          0
                                          down vote










                                          up vote
                                          0
                                          down vote









                                          Thread.sleep is static method ...



                                           Thread t2 = new Thread(() -> 
                                          try
                                          Thread.sleep(1000);

                                          catch (InterruptedException e)
                                          );





                                          share|improve this answer












                                          Thread.sleep is static method ...



                                           Thread t2 = new Thread(() -> 
                                          try
                                          Thread.sleep(1000);

                                          catch (InterruptedException e)
                                          );






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered 59 mins ago









                                          niemar

                                          152213




                                          152213











                                          • that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
                                            – Carlos Heuberger
                                            15 mins ago

















                                          • that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
                                            – Carlos Heuberger
                                            15 mins ago
















                                          that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
                                          – Carlos Heuberger
                                          15 mins ago





                                          that is not the point. It is a method of Thread but the Lambda is being defined in the user class, just being used to create a Thread
                                          – Carlos Heuberger
                                          15 mins ago


















                                           

                                          draft saved


                                          draft discarded















































                                           


                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52602990%2fwhy-cant-we-call-threadsleep-directly-inside-a-lambda-function%23new-answer', 'question_page');

                                          );

                                          Post as a guest













































































                                          Comments

                                          Popular posts from this blog

                                          What does second last employer means? [closed]

                                          List of Gilmore Girls characters

                                          Confectionery