2

There are two ways I know of to create Threads.

1.

    Thread thread = new Thread()
    {
     @Override
     public void run()
     {
      //do something;
     }
    };
  1.  Thread thread = new Thread(new Runnable()
     {
      @Override
      public void run()
      {
       //do something;
      }
     });
    

What I am asking is that, are there any differences in these methods, like which one is more efficient regarding Memory usage, CPU usage (if there is any difference), etc.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
Miles Morales
  • 307
  • 1
  • 15
  • 8
    basically, your question is: should I extend Thread, or should I implement Runnable. Unless you plan on altering default behavior of the Thread class (which in about 99% you really don't want to do) do NOT extend Thread, always go for an implementation of Runnable. – Stultuske Jun 25 '20 at 05:18
  • No it doesn't answer my question! – Miles Morales Jun 25 '20 at 05:21
  • Please read it properly. Moreover, both are same just you are using an interface and class. – Anish B. Jun 25 '20 at 05:22
  • 6
    @PeterParker it should, actually. you are asking the difference between an anonymous class extending Thread, and an anonymous class implementing Runnable, that link is exactly what you should read. – Stultuske Jun 25 '20 at 05:27
  • The memory and CPU usage will be exactly the same (maybe a difference of a few bytes on the memory side, but it is completely insignificant compared to the size of the JVM for example). Use the second construct, it's cleaner. – assylias Jun 25 '20 at 05:28
  • 2
    These days (Java 8 and later), `new Thread(() -> { /*do something*/ })` would be better. Or the *method reference* equivalent. Both saves the creation of an anonymous class. – Andreas Jun 25 '20 at 05:35
  • @Dioxin Both are anonymous classes. – Andreas Jun 25 '20 at 05:38
  • What does this 1uestion have to do with swing? Please remove the swing tag. – NomadMaker Jun 25 '20 at 05:39

0 Answers0