1

I have a Class m2 which implements runnable and can be called with both run() and start() . Now i have read about “implements Runnable” vs. “extends Thread” , and what i'm asking here is

  1. start() vs run() for class m2
  2. how they compare with (as in when to use) an anonymous call like the one below.
public class test1{
    public static void main(String[] args){
        // m2
        new m2().run();
        new Thread( new m2()).start();
        // anonymous
        new Thread(new Runnable(){
            public void run(){
                System.out.println("anonymous code looks real cool!");
            }
        }).start();
    }
}


class m2 implements Runnable{
    public void run(){
        System.out.println("hello from m2");
    }
}

ps I'm putting in "multithreading" because i couldn't find a "thread" tag.

Community
  • 1
  • 1
Somjit
  • 2,503
  • 5
  • 33
  • 60

4 Answers4

2

new m2().run();

This runs the run() method of the m2 object (assuming m2 extend Thread instead of implements Runnable) - but in the current thread, instead of actually starting a thread and running it there.

how they compare with (as in when to use) an anonymous call like the one below.

Use anonymous implementations for small/trivial things that aren't used in multiple places. If it's complicated enough that you'd ever want to test it, it's probably worth moving to a non-anonymous class.

James
  • 8,512
  • 1
  • 26
  • 28
2
  1. You can't invoke start() on Runnable instance, Runnable doesn't have start() method. If you are talking about invoking Thread.run() and Thread.start(), then start() spawns a new Thread (realtime) but run() executes the statements within run() sequentially.

  2. Coming to anonymous class vs the named class, its just a coding style. People prefer anonymous class to write fairly small interface implementation

sanbhat
  • 17,522
  • 6
  • 48
  • 64
1

.run() will execute the method and .start() will start the thread that will execute run()

AppX
  • 528
  • 2
  • 12
0

Threads can be implemented by extending Thread class, implementing Runnable interface and Callable interface.

If you want to return an value or throw an exception then use Callable otherwise use Runnable as extending Thread class limits the Class inheritance and also makes the process heavy.

Below link can be useful if you want to find more: Different ways to implement Threads in Java

Aashish
  • 7
  • 2