Implementing Runnable interface  Vs  extending Thread class

hi,
i've come to know by some people says that Implementing Runnbale interface while creating a thread is better option rather than extending a Thread class. HOw and Why? Can anybody explain.?

Its the same amount of programming work...
Sometimes it is not possible to extend Thread, becuase your threaded class might have to extend something else.
The only difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.
http://developerlife.com/lessons/threadsintro/default.htm#Implementing

Similar Messages

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • How can I know a class which implements Runnable interface has terminated?

    Hello! I have a class which has implements Runnable interface, while I want to execute some operation when the thread has terminate in multithread enviroment.How can I know the thread has terminated?Does it give out some signal?Cant I just call my operation at the end of the run() method?

    I want to execute some operation when
    the thread has terminate in multithread enviroment....
    Cant I just call my operation at the end
    of the run() method?Sure. Before run() ends, invoke that other operation.
    How
    can I know the thread has terminated?Does it give out
    some signal?Not that I'm aware of, but you can do what you described above, or I believe a different object can call isAlive on the thread.

  • Implementation of DragManager in extended Panel class

    Hi,
    I'm facing a problem during implementation of DragManager in
    extended Panel class. I've a component which is extending the Panel
    class where I've attached four Images with their corresponding
    dragging features.
    Say, the four images' x positions as these: x1 = 10, x2 = 20,
    x3 = 30, x4 = 40. After adding the DragManger class and
    implementation of dragging feature to those Images, the dragging is
    works fine. But, the problem is, when I'm dragging x1 image, the
    imageProxy associated to x1 starts showing from exactly the x1
    position, but also all the three images' (x2, x3, x4) imageProxy
    starts dragging from x1 position only! When the expected result is,
    the x2 imageProxy shud starts drag from x2 x position itself, and
    for other x3 imageProxy from x3 position and x4 is their also.
    Except the x1 image, all the other three's imageProxy are not
    starts from their respective image x position.
    Anyone can give any idea.. how to overcome this?
    tnks.
    ASB

    What are the:
    DragManager.doDrag(initiator, ds, event, imageProxy, x, y,
    1.0);
    x and y parameters in your drag manager's doDrag method? They
    should be calculated from the point of mouse click that would
    event.localX and event.localY.
    ATTA

  • Creating thread by extending thread class?

    HI
    What is the differnce in run() method in the thread class and
    public void run() method in ruble interface is both are same or saparete?
    is the run() method in the Thread class overridden method from Runnable interface?
    Thns

    It's a difference in paradigm. If you are changing the behaviour of how Thread works, extend from Thread.
    If you're implementing a system where you're using Thread instances to control some process, implement Runnable.
    In the vast majority of cases, that means you'll be implementing Runnable.
    The exception might be if you're writing an application server, or a process manager of some sort.

  • Implementing DOM Interface with existing Java classes

    I had planned on using some tree-like Java classes as a Document Object Model, which would give me access to all sorts of XML and DOM tools like parsers and XSLT transformers. Initially, I thought all that would be neccessary is to implement all the DOM Interfaces in org.w3c.dom and then I would have a set of classes that conformed to DOM Level 1. It was my understanding that interfaces such as DOMImplementation and Document would interface with various XML tools, allowing creation of a class that implements Document and then Document would have its various factory methods that know how to create the various DOM nodes such as Element, Attr, Text, NamedNodeMap, NodeList, etc.
    The problem I'm seeing now is that the JAXP specification (which is what the latest Xerces and Xalan tools conform to) has something called a DocumentBuilder and DocumentBuilderFactory that appear to be necessary to tell the framework what type of class to instantiate that implements the Document DOM interface. Those appear to have a lot of methods that deal with parsing of XML documents and I didn't really want to write or even subclass any existing Parsers in order to get the functionality of traversing and transforming a set of classes that implement the DOM interface.
    Am I missing something here? Is it possible to plug in any (set of classes for) DOMImplementation and get them to work with the various DOM and XML tools out there?
    Is there an easier way to allow parts of an application access to internal data structures but have the more generic tools or APIs, such as XSL transformers, access that same set of classes as a DOM with the generic DOM interface methods?
    Can someone provide me with some guidance here? I'm in the process of finalizing some design on a system and need to know if this is possible or if I need to alter my design.
    Thanks.

    If I understand you correctly, I think I am working on a similar issue. I am unhappy with the methods given by the DOM for retrieving data from the XML file and for building a file. Our software has a bunch of code that uses these classes and it is extremely ugly. My solution was to create a facade on top of the DOM model. Essentially I have some simple classes that store all the pertinent info (for me) about the XML structure. Essentially that is the element or attribute name, its values and in the case of the element, it's children. This makes it easier for me to build and retreive the data. What I then built was a loader class and a builder class. The loader takes an XML file and parses it in using the DOM classes and builds a structure using my classes and returns the root element. The builder takes a root element and creates a DOM object out of it. This frees me of having to code around the DOM classes all over the place and makes it simple to upgrade our XML code if the DOM changes or a better DOM is released. I am using factories to facilitate this and allow me to have loaders for specific types of XML documents so that I can have a class for each which further simplifies the XML related tasks of other developers on my team.

  • Class constructor that implements an interface returns an  "interface", why

    Hi,
    I am studying some code that I need to understand well. This code works, I just don't understand the following:
    A class was defined extending an interface as so:
    public class GeometricShape implements Area {
    // constructor
    public GeometricShape() {
    System.out.println('bla);
    In another file, GeometricShape class was instantiated as follows:
    public class ExampleUse {
    Area g = new GeometricShape();
    My qustion is, why does the code above expects "new GeometricShape()" constructor to return an interface of type Area?
    Can someone explain?
    thanks

    Can someone explain?When a class implements an interface, or extends another class, or when a interface extends another interface, it means that anywhere an instance of the parent class or interface is expected, the child can be used.
    Wherever a Mammal is expected, you can provide a Dog or Cat or Whale or Human or NakedMoleRat. Each of those is a mammal.
    If you say "give me some food," and you don't specify anything else, the person you're talking to can hand you a hamburger or an apple or a bowl of rice. Any of those will meet the requirements you put forth.
    This is how the OO "is-a" relationship maps to Java.

  • Implement Runnable

    I think the often given advice of implement Runnable rather than extend Thread (unless it is some kind of Thread!) is good advice, but sort of incomplete.
    Alice wrote:
    class A {...}Bob writes:
    class B extends A {...}Alice improves class A:
    class A implements Runnable
      // Do the A-something in another thread
      new Thread( this ).start();
      public void run() {...}
    }Everything is fine, the contract of class A did not change (or did it?).
    Bob improves class B:
    class B implements Runnable
      // Do the B-something in another thread
      new Thread( this ).start();
      public void run() {...}
    }Now the A-something is not done anymore and the B-something is done twice!
    I think the complete advice should be to prefer inner classes that implement Runnable.
    class A
      // Do the A-something in another thread
      new Thread( new Runnable {
         public void run()
             doTheASomething();
      } ).start();
      private void doTheASomething() {...}
    }Any thoughts?

    More I think about it, the problem is more general.
    Implementing yet another interface in a class should
    d not be taken lightly and I must confess, I used to
    take it lightly. Adding new public methods, who
    should care? Seems that when we implement an
    interface we do more than just add a few public
    methods. The contract does change!Yes and no, IMO.
    If a given method synchronously would return a value, then obviously the asynchronous version cannot. (You could have a callback or some other notification mechanism to get the value formerly returned). So in a formal sense, there is now an additional contract, should a given class choose to realize that interface. However, the original synchronous contract presumably remains unchanged.
    Further, if you implement a given interface, you must honor its contract. The contract itself does not change. You simply realize an implementation of it.
    - Saish

  • Runnable v/s Thread class.

    Hi ya Folks,
    Any MAJOR difference between using the Runnable interface
    or extending the Thread class?
    Which is more beneficial.?

    From the infamous cut-n-paste archive...
    Prefer implementing Runnable to extending Thread. Think of Threads as the workers and Runnables as the job itself. You implement Runnable because your "unit of work" or whatever you want to call it IS-A Runnable -- that is, something that will do its job start-to-finish when you call run. You would only extend Thread if your class IS-A Thread -- that is, it has a reason to do everything Thread does, and you need to slightly add to or modify Thread's behavior.

  • Runnable Vs Thread Class

    Hello All,
    I have a doubt regarding Runnable and Thread class. As we all know Java provides two ways to run Threads. One way is to extend Thread class and the other way is to implement Runnable Interface.
    Apart from the OOPS funda, does java have any other concept in providing two ways to run threads ?. I mean, we very well know that if we extend Thread class, we may not be able to extend any other class in Java . So if we implement Runnable interface,we can extend or implement any other Interface or class. Apart from this reason, does Java has any other concept in providing two ways to run threads ??
    Please share your knowledge
    Thanks and Have a Nice Day,
    Regds,
    Sai

    As far as I know, that's the only reason for the two options--one gives you flexibility in your class hierarchy, the other saves you a few lines of code. Personally, I always implement Runnable. The few lines of code saved seem trivial to me compared to "cleaner" OO (IMHO), but maybe somebody else has a better reason to extend Thread.

  • Extending Applet implements Runnable    --explain

    kindly give an explanation of the need to use the
    <extends Applet implements Runnable > code
    while creating an applet program is there a need to use both Applets and Runnable
    wht are the methods available in Applet class
    and Runnable interface

    The most common use of the Runnable interface is for threading.
    An applet doesn't need to implement Runnable to be run as an Applet, but an applet often needs to be doing things in the background, not just when specific user events like init, start, mouse events etc. come in. For example the applet might run some kind of animation.
    An applet should return promptly from events of the above sort, allowing the browser to get on with it's own business. If it is to do something itself one of these events needs to start a thread.
    Declaring the Applet runnable allows you to do something like:
    new Thread(this).start();for example in the init method. This starts a new thread of execution which runs the run method of the applet, which will do the background activity.
    You don't have to do it this way, you can create another Runnable object whose run method will be executed by the thread. Often you use anonymous classes for this e.g.
    new Thread(new Runnable() {
       public void run() {
              doBackgroudStuff();
        }).start();

  • Extends thread and Runnle Interface

    In java there 2 ways to create thread
    1.Extending thread
    2.implements runnable interface
    What is difference between the 2 approaches? which one to use where?

    public class ThreadTest extends Thread {
      public void run() {
      public static void main(String[] args) {
        ThreadTest tt = new ThreadTest();
        tt.start();
    public class ThreadTest extends Runnable {
      public void run() {
      public static void main(String[] args) {
        ThreadTest tt = new ThreadTest();
        Thread t = new Thread(tt);
        t.start();
    }The difference is how you start the thread when you code it. if you extend Thread, you can call its run method directly. When you extends Runnable, A wrapper is needed to start the thread.
    The Runnable approach is used when your class is extending another class (eg. JFrame). Since Java do not support multiple inheritance, you can write something like public class MyProg extends JFrame implements Runnable, and still have a thread.

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Assigning ThreadGroup to a Class that Extends Thread

    How can i assign a thread group to a class running as a thread that extends thread without changing the class to implement Runnable?
    An Example of the application format:
    public class Application implements Runnable
    private ThreadGroup main = new ThreadGroup("Main");
    private Thread mainThread = null;
    public Application()
    public void start()
    if (mainThread == null)
    mainThread = new Thread(main,"main")
    mainThread.start();
    public void run()
    Thread current = Thread.currentThread();
    while(current != null)
    while(something to do)
    AThread a = new AThread();
    a.start();
    String aData = a.getData();
    BThread b = new BThread(data);
    b.start();
    String bData = b.getData();
    class AThead extends Thread
    public AThread()
    //What to do with AThread to assign it to a thread group?
    public void run()
    Basically the application works form a main constructor class running the application class as a thread. The application class will then launch AThread and BThread as subthreads. I would like to be able to count how many of each type of thread is running for the AThread and BThread. I tried using AThread and BThread implementing Runnable to create a thread under a group but it wouldn't work. The application class needs to get information from the AThread and BThread threads once the thread was done, but if the AThread and BThread was implementing Runnable, the Applicaiton Class can't get the data or run methods. Is there some way i can assign what thread group AThread and BThread will run as in thier class files and not the Application class?

    See: http://java.sun.com/j2se/1.4/docs/api/java/lang/Thread.html#Thread(java.lang.ThreadGroup, java.lang.String)
    I think this does what you want:
    public class Application implements Runnable
    private ThreadGroup main = new ThreadGroup("Main");
    private ThreadGroup aThreads = new ThreadGroup("AThreads"); // Added a thread group for all AThread objects
    private Thread mainThread = null;
    public Application()
    public void start()
      if (mainThread == null)
        mainThread = new Thread(main,"main")
        mainThread.start();
      public void run()
        Thread current = Thread.currentThread();
        while(current != null)
          while(something to do)
            AThread a = new AThread(aThreads);  // Create an AThread that will belong to aThreads ThreadGroup
            a.start();
            String aData = a.getData();
            BThread b = new BThread(data);
            b.start();
            String bData = b.getData();
    class AThead extends Thread
      public AThread(ThreadGroup group)
        super(group, "AThread"); // This will make a new Thread that belongs to ThreadGroup group, see link above
      public void run()
    }

  • How can I implement This? - Via Multiple Threads

    Hi Friends,
    I m getting a list of 4000 emails in an ArrayList. Now I want to put 300 addresses in a mail at a time, and Want to create a new Thread and Send a Mail.
    I want to run 20 threads at a time to do so, Means Each thread is taking 300 addresses from array assigning it to Message and send it. After Sending it should return to ThreadPool.
    Also the 300 addresses should be removed from arraylist.
    Here are code snippet, i m using..
    MailBean.java - A bean which have all the MailProperty and Send Method.
    MailSender.java - It implements Runnable Interface, In its constructor A MailBean Object is Created and in run method it is sending the Mail.
    FileReader.java - It extends ArrayList, it takes a fileName, parse the Emails add email.
    Main.java - Here i want to send mails using ExecutorService class of java.util.concurrent.
    Mailer.java (Main Class)
    public class Mailer {     
         private final FileReader toEmails;
         private ArrayCollection<String> emails ;
         public Mailer(String addressFile){          
              toEmails = new FileCollection(addressFile);
              emails = new ArrayCollection<String>();
                          Here I want to read the 300 emails from toEmails append it in a String and add it to emails ArrayCollection.
        public static void main(String[] args) {
            try{
                 BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(200);
                 Executor e = new ThreadPoolExecutor(50, 50, 1, TimeUnit.SECONDS, queue);
                    if (args.length != 1) {
                         System.err.println("Usage: java ExecutorExample address_file" );
                         System.exit(1);
                  Mailer mailer = new Mailer(args[0]);
                  MailBean bean = new MailBean();
                  bean.setSubject("Mail Bean Test");
                  bean.setMessage("Hi This is a Test Message, Please Ignore this Message");
               /*  I want to run the send mails to all the emails (300 emails per String.) with the Exceutor.
                   Can somebody tell, I want a new object of MailSender for each mail
                   and sendmails
                 System.out.println("Creating workers");
                 for(int i = 0; i < 20; i++)
                     e.execute(new MailSender(bean));
                 System.out.println("Done creating workers");
            }catch(Exception ex){
                 ex.printStackTrace();
    } Can Somebody give me hint, How can we do it?

    The problem is the sound buffer. You may stop the method which dispatch the notes to be played... but not clear your sound card buffer....
    anyway: you should implement it in daemon threads. This way you can control the thread suspend, stop, restart, etc.
    use Thread.sleep(milliseconds);

Maybe you are looking for

  • Office Web Apps Integration

    Hello, We are looking to deploy Office Web Apps to integrate with Exchange and share files but I do have a few questions before I deploy this technology. With this server installed on premise, will this give the users the ability to access the Web Ap

  • Need information about some address fields in DQXI

    I need to know the 'Content type' and 'Data field name' of the following address fields in DQXi 1. Alley 2.Building 3. HouseNumber 4. HouseSuffix 5. Lane 6. Pob Line 7. PobNumber 8. Section 9. PrefectureCode 10.DistrictName 11.Mail Stop 12. Postal Co

  • Can FCP X export .m4v directly?

    Can FCP X export .m4v directly without usig Compressor?

  • Gridwars on arch x86_64

    hi, i wanted to play gridwars2 today. downloaded, unzipped and tried to execute it ... error: ./gridwars: error while loading shared libraries: libstdc++.so.5: wrong ELF class: ELFCLASS64 can anybody help me fix this? i love this game! do i need a bi

  • Mountain Lion monitors bitmapped

    Hi, I have a Mac Pro 2008 model, I was on Snow Leopard until recently, skipped Lion and just installed Mountain Lion, now my two Samsung 920N monitors are almost impossible to look at, they are nearly as bad as 1980's bitmapped but blurry and ghosted