nobalG
nobalG

Reputation: 4620

Difference between the thread creation phenomenas and starting them

What is the Difference between the two thread creations in the code below:

public class MyThread extends Thread 
{
    int a=0;

    public void run()
    {
        System.out.println("Some Thread");
    }

    public static void main(String[] args) 
    {

        MyThread m=new  MyThread();

        Thread t=new Thread(m);
        m.start();     //what is difference between this
        t.start();     //and this

    }   
}

Both are giving me the same output.

Upvotes: 0

Views: 73

Answers (5)

Solomon Slow
Solomon Slow

Reputation: 27115

When you pass a Runnable object into the Thread(r) constructor, the Runnable becomes the thread's delegate. These days, delegation is considered to be a more powerful, more flexible way to organize a program than inheritance. That's especially true in Java where there is no multiple inheritance.

When you give the thread a delegate, the delegate can also inherit from some other class (as shown in user2794960's example). But if you make your "thread" class inherit from Thread, then it can't also inherit from any other.

You know you're dealing with delegation when you say Foo has a Bar instead of saying Foo is a Bar.

Upvotes: 1

Martina Varsanyi
Martina Varsanyi

Reputation: 11

There are several possibilities to pass a Runnable implementations to a Thread and start it as a Thread, but in your example it just uses some extra CPU time. It would make sense to use in a situation like the one below.

class MyClass extends OtherClass implements Runnable { .. }

MyClass mm = new MyClass(..);
Thread t = new Thread(mm);
...

Upvotes: 1

Vicky
Vicky

Reputation: 3310

If you have created

Thread t = new Thread();

Then the run method would not do anything as Thread's run method is

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

where the target is null. If you pass a target

Thread t = new Thread(target)

then thread would execute the target's run method.

If you have extended MyThread then run method in MyThread would execute

Upvotes: 1

Eran
Eran

Reputation: 393781

The thread instance would be of different type in the two cases - MyThread vs. Thread - but the run method to be executed when you start the threads would be the same.

When you create a Thread with new Thread(m), you don't have to pass a Thread instance. You merely have to pass an instance implementing the Runnable interface.

Upvotes: 3

Jean Logeart
Jean Logeart

Reputation: 53819

It is eventually the same behavior.

Thread implements Runnable and Thread has constructor that takes a Runnable. Therefore new Thread(m); uses the Runnable implementation of its argument. But eventually the same run method is used, only the Thread instances are different.

Upvotes: 1

Related Questions