-1

I've been checking some technical stuff about Threads in Java and I'm a little bit confused about a specific issue when I define a thread with an anonymous class (proper use of parenthesis in the constructor definition). The regular declaration would be this one:

    Thread myRunnableThread3 = new Thread(new MyRunnable(){
        @Override
        public void run() {
            System.out.println("myRunnableThread3!");
        }
    });
    myRunnableThread3.start();

And just for experimentation purposes, I tried this:

    Thread myRunnableThread3 = new Thread(new MyRunnable()){
        @Override
        public void run() {
            System.out.println("myRunnableThread3!");
        }
    };
    myRunnableThread3.start();

As you may see, both look pretty similar and the output console it's the same. So, Am I missing something? maybe there is a little slightly functional difference that I'm not realizing yet. By the way, I'm using Java Corretto 11. Both look OK, maybe should I go for the first option? Thanks for your comments and help.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
raymx007
  • 3
  • 1
  • 2
    they are different as they create an anonymous class of different things: `MyRunnable` and `Thread`. Neither is OK, if you ask me. It is a lot simpler to just `Thread myRunnableThread3 = new Thread(() -> System.out.println("myRunnableThread3!"))` – Eugene Mar 12 '21 at 18:02
  • "*What's the best way*" questions are usually opinion-based, and hence, [off-topic](https://stackoverflow.com/help/on-topic). – Giorgi Tsiklauri Mar 12 '21 at 18:07

2 Answers2

2

The first is creating an anonymous subclass of MyRunnable.

The second is creating an anonymous subclass of Thread, which requires that MyRunnable is instantiable; and MyRunnable wouldn't actually then be used at all, because it's not invoked in the run() method you're defining in the Thread subclass.

There is no reason to subclass Thread, and presumably you want some special behavior from your MyRunnable base class (although the only thing that would provide special behavior that would actually be run is the constructor).

Use the first way.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Yes, indeed. I didn't realize that specific detail. Even when they look pretty similar (at least for a newbie like me), the parenthesis isolates the constructor and the class declaration body. Thanks! Eventually, I will master lambda expressions, and functional interfaces will help me a lot with this kind of stuff. – raymx007 Mar 12 '21 at 18:18
0

You can also use a lambda expression to start a thread.

Thread myRunnableThread3 = new Thread(()-> {
    System.out.println(Thread.currentThread().getName());
    System.out.println("myRunnableThread3!");},"MyThread");

    
myRunnableThread3.start();

Prints

MyThread
myRunnableThread3!
WJS
  • 36,363
  • 4
  • 24
  • 39