whats the advantage of implementing runnable over extending thread

Recommended Answers

All 4 Replies

It allows you to extend some other class, if that's important to you

Extending Thread indicates (in OO design) that you're changing the behaviour of Thread itself.
You rarely if ever want to do that.

For most if not all purposes you'll ever encounter, implementing Runnable is the correct thing to do.

JAVA supports multitasking by using threads. In order to create a thread you have coded, you can either use

class XYZ implements Runnable

or

class XYZ extends Thread

both of the coding have similar effects except:
1. if you use implements Runnable, you HAVE TO override the method named "public void run()"
2. if you use "extends Thread" you can just call any methods in Thread class like "sleep(100)" directly but if you decide to use "implements Runnable" way, you have to indicate the container class of the method like "Thread.sleep(100)", since the methods are not inherited to your class
3. if you use "extends Thread" in your class definition, than you can directly call the .start() method by the object referrer. On the other hand, "implements Runnable" decision requires an additional object referrer pointing to a Thread object. (let me give a code sample to get into detail):

class XYZ extends Thread{

}
class ABC implements Runnable{
  public void run(){
  }
}
//www.bilgisayarkavramlari.com
public class Test{
  public static void main(String args[]){
    XYZ xyz = new XYZ();
    ABC abc = new ABC();
    xyz.start();
    Thread t = new Thread(abc);
    t.start();
  }
}

Above code can give you an idea about the situation.
XYZ does not need a run method while it is required in ABC. (Else you get a compile time error)
You can directly call xyz.start() and you can not call abc.start() but you have to create a Thread containing your Runnable object and than call the start method of this Thread referrer like t.start() in above code.

Also the comment of JamesCherrill is absolutely correct, the most useful effect of deciding "implements Runnable" way is using the extends keyword for another class, since JAVA does NOT support multiple inheritance.

@shedai
the sleep method is static, so you don't need to have one running (well, for the purists among us, I mean other than the main-thread) to call the sleep method.

all that really had to be said, as an answer to the OP's question, has been said by JamesCherril and Jwenting.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.