-1

Could you please give a short explanation of whether there is a significant difference between the following thread implementations:

// Method 1
Thread aThread = new Thread()
{
    @Override
    public void run()
    {
        // do some work
    }
};

aThread.start();

// Method 2      
Thread bThread = new Thread(new Runnable()
{
    @Override
    public void run()
    {
        // do some work
    }
});

bThread.start();

I tried to find similar questions in stackoverflow, but couldn't succeed. Sorry, if it is already discussed before.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Ayaz Alifov
  • 8,334
  • 4
  • 61
  • 56
  • and here: http://stackoverflow.com/questions/21871073/java-thread-vs-runnable – Jared Burrows Jul 21 '15 at 14:09
  • @MarkW , Please read the links I posted before making a comment. Here is a good example: http://stackoverflow.com/a/15226278/950427 from the links I provided. – Jared Burrows Jul 21 '15 at 14:13
  • Jared Burrows, thank you for your comments, but I don't find them the same as my example. At least because I use threads in both methods, but in your methods - one is Thread and another one is Runnable. – Ayaz Alifov Jul 21 '15 at 14:18
  • and another: http://stackoverflow.com/questions/30553051/why-should-i-use-runnable-instead-of-thread – Jared Burrows Jul 21 '15 at 14:21
  • 1
    There's no difference at all. Actually, both apporaches are equally bad practise. You should use an `Executor` or `ExecutorService` instead. – fps Jul 21 '15 at 14:24
  • 1
    Jared Burrows, please explain why it is the same? Federico Peralta Schaffner, thank you for your answer. But could you please explain why it is bad practise? – Ayaz Alifov Jul 21 '15 at 14:27
  • 1
    @SaQada https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html `Executor` abstracts away the details of `Thread` creation and management. – Tripp Kinetics Jul 21 '15 at 14:36
  • @FedericoPeraltaSchaffner, I've never seen a use-case for `Executor`, but `ExecutorService` is an interface for a _thread pool_. Thread pools have their uses, but they are not a silver bullet that solves all threading problems. (Hint: If `ExecutorService` solves all problems, then why did they also give us `ThreadFactory`?) I would not use a thread _pool_ in cases where I want a single `Thread` that runs for the entire lifetime of the program. – Solomon Slow Jul 21 '15 at 16:45

1 Answers1

1

As per the Javadoc:

https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#run--

the default run() method of Thread executes the run() method of the Runnable it was created with, if it exists. Otherwise it does nothing. What this means is that creating a Thread with a Runnable does the same thing as overriding Thread's run(), except it uses slightly more stack for the additional function call.

So no. No significant difference.

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37