Pregunta

Heres the code about threads.....I dont know the difference between those 2 new() statements.

  Runnable r=new Runnable() {
    public void run() {
    System.out.print("Cat");
    }
    };

    Thread t=new Thread(r) {
    public void run() {
    System.out.println("Dog");
    }
    };
    t.start();

Output is Dog But why and how ?

¿Fue útil?

Solución

Because you override Thread#run(), so this method is eventually executed when you start the thread. The default Thread#run() delegates to the passed-in Runnable. Rule of thumb: Either provide a Runnable or override Thread#run(), but don't do both!

Otros consejos

In the thread t , you override the run method of runnable which are passed to it . I think this is why when you call the start of a thread which has a runnable and its run method is not called !

In the first "new" statement your creating a Runnable instance which your later passing into the Thread created in by the second "new" statement. The output is dog as in your second "new" statement where your creating the Thread, you are also overriding the run() method, this must take precedence over the implementation of run() inside the Runnable which you passed in. This means your Runnable implementation of run() which prints Cat is never used, only the run() implementation printing Dog is invoked by the Thread.

change to:

Runnable r=new Runnable() {
public void run() {
System.out.print("Cat");
}
};

Thread t=new Thread(r);
t.start();

this should print "Cat"

while creating Thread object for instance t you've override run() method. so calling t.start() will execute overridden method. So the output is Dog and not Cat

Change it to:

new Thread(new Runnable() {
    public void run() {
        System.out.print("Cat");
    }
}).start();

The Runnable interface provides an alternative method to using the Thread class, for cases in which it's not possible to make your class extends the Thread class. This happens when our class, we want to run on a separate thread should extend some other class. Since there is no multiple inheritance, our class can not simultaneously extend the Thread class and another. In this case your class must implement the Runnable interface.

Since Runnable is an interface and Thread is a class, there are some differences related to how JVM manages them.

-If you implements Runnable interface, a unique object will be shared between threads.

-Extending Thread class, every thread will create an object.

In some scenarios runnable will consume less memory than Thread. Furthermore, I think that if you extend a class, it's because you'd want to override some methods, so from my point of view if you won't modify any method or behavior from Thread class, you should use Runnable..

Hope it helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top