0

When working with Threads, it is fairly common to write something like this:

Runnable r = new Runnable()
{
    public void run() { /* ... */ }
};
new Thread(r).start();

This is all nice and correct, but I believe the same could be achieved in a more performant and easy way:

new Thread()
{
    public void run() { /* ... */ }
}.start();

However, I almost never see anything like this in code examples using Threads and Runnable. Is there any technical or style-related reason to use the first example instead of the second?

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
  • 2
    Because maybe your class does already `extends` another class. – Turing85 Jul 26 '15 at 16:34
  • Something I noticed about `Thread` is unlike `Runnable` it is not needed to invoke the swing components. And using much `threads` increases CPU usage more than `runnables` – Rahul Jul 26 '15 at 16:37
  • More performant? Probably not. Easier? Yes, but then that's what makes it so damned hard to maintain the legacy code that I have to work with every day Somebody took the easy way out instead of taking the time to make it flexible, testable, scalable, extensible,... – Solomon Slow Jul 27 '15 at 13:18

2 Answers2

2

Because

Runnable r = new Runnable()
{
    public void run() { /*your code */ }
};
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();

is equal to

new Thread()
{
    public void run() { /* ... */ }
}.start()
new Thread()
{
    public void run() { /* ... */ }
}.start();

new Thread()
{
    public void run() { /* ... */ }
}.start();
new Thread()
{
    public void run() { /* ... */ }
}.start();

They are not exactly equal. In the first case all threads share the same runnable in the second, they don't. In the first case, write to a volatile field (or if a happens-before exists), will be visible to other threads.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jishnu Prathap
  • 1,955
  • 2
  • 21
  • 37
  • 1
    Nope... Not exactly true.. In the first case all threads share the same *runnable* in the second, they don't. In the first case, write to a *volatile* field (or if a *happens-before* exists), will be visible to other threads. – TheLostMind Jul 26 '15 at 16:39
  • Its *almost* equivalent to `new Thread(new Runnable)` – TheLostMind Jul 26 '15 at 16:44
1

Basically Thread class also extends the same Runnable interface so same behavior of the Thread class you can also achieve by implementing Runnable interface insated directly extending Thread class and implementing run method. Moreover you can extend some other class and implement more interface also.

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23