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.

Similar Messages

  • 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.

  • 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

  • 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 to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • Help! how to refresh the JTable of a class from another thread class

    there is an application, in server side ,there are two classes, one is a class called face class that screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much

    thank you very much !
    i tried it ,but the TableModel i used like this ,and how to change the TableModel?
    here the files of mine ,pls give me some help,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write?? }
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

  • Runnable and Thead Class

    what is the Advantages of using Runnable Interface and the Thread Class?
    Please let me know this....and when to use which one..
    Thanks
    satish

    It should be explained in any decent tutorial or Book:
    http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java
    But in case none of the above explains it the short version is that unless you actually need to change Threads behavior (i.e., override one or more of its methods, or add new methods) then you should use Runnable.

  • Runnable a thread?

    Is a class that implements Runnable itself a thread?
    When i invoke run() method of a class that implements Runnable does it behave like a thread?
    Or only Runnable object wrapped by Thread class is a Thread?

    Is a class that implements Runnable itself a thread?Implementing Runnable is another way of writing threads, if you implement runnable you dont need to extend Thread, as a matter of fact it is considered the better way for writing threads. But thats another discussion
    >
    When i invoke run() method of a class that implements
    Runnable does it behave like a thread?
    use start
    class PrimeRun implements Runnable {
             long minPrime;
             PrimeRun(long minPrime) {
                 this.minPrime = minPrime;
             public void run() {
                 // compute primes larger than minPrime
    PrimeRun p = new PrimeRun(143);
         new Thread(p).start();

  • 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.

  • Why wait() is there in Object class why not in Thread class

    why wait() is there in Object class why not in Thread class .
    while we use wait() in the case of thread environment?
    If there is any situation where we use it without using threads please mention with example. or link to that example..

    839091 wrote:
    The question still remain un-answered as the answers provided are not clear. Can anybody explain why wait(), notify() methods are available in Object class and not thread?What part of the answers given did you not understand?
    Have you even tried writing any code that uses wait/notify and thought about how you'd write the same code if they existed only on Thread rather than on Object?
    Have you studied the basics of Java's multithreading?
    Do you know what a lock is?
    Do you know what the synchronized keyword does?
    Do you understand the relationship between synchronized and wait/notify?
    If you can answer yes to these questions, then the reason that wait/notify exist on Object should be obvious. So, which of the above are "no"?

  • Extending the Thread class

    i would like to do that
    1) One thread displays "ABC" every 2 second;
    2) The other thread displays DEF every 5 seconds;
    i need to create the threads by extending the Thread class ...
    thank you for your help ,
                public class Thread1 extends Thread {
              public Thread1(String s ) {
                   super (s);
              public void run() {
                   for ( int i=0; i<5; i++ ) {
                        System.out.println(getName());
                        try {
                           sleep ((long) 5000);
                        } catch (InterruptedException e ) {
                           /* do nothing */
              public static void main (String args[]) {
                   new Thread1 ("ABC").start();
                   new Thread1 ("DEF").start();
         }     

    I think he has been told to use the Thread class by the sounds of it.
    public class Thread1 extends Thread {
         public Thread1(String s ) {
              super (s);
         public void run() {
              for ( int i=0; i<5; i++ ) {
                   System.out.println(getName());
                   try {
                      sleep (getName().equals("ABC")? 5000 : 2000); //If you don't understand this then Google for "Java ternary operator"
                   } catch (InterruptedException e ) {
                      /* do nothing */
         public static void main (String args[]) {
              new Thread1 ("ABC").start();
              new Thread1 ("DEF").start();
    }

  • "Safe" delete of Thread class from a Vector

    I need to be able to delete a thread class object from a vector.
    1) Is it safe to do so immedately after calling xyz.stop() ?
    2) If so, does Java clean all the thread stuff up automatically ?
    3) If not, is there something else I should do to clean up?

    The stop method of class Thread is deprecated, however it's still possible to stop this thread. A thread's memory should become available for garbage collection the moment it is no longer executing, and it is no longer being reffered to.
    To stop your thread, you need to set a boolean flag that is available to it to false:
    Thread myThread = new Thread()
         public boolean stopRunning = false;
         public boolean threadComplete = false;
         public void run()
              while(!stopRunning)
                   doSomething();
              threadComplete = true;
    }If you are doing something involving blocking I/O inside your thread, you're going to need to interrupt the thread after setting this public flag to true in order to get it to stop executing.
    Then you can simply remove it's refference from that Vector, and it will become elligable for Garbage collection the moment it becomes inactive.
    -Jason Thomas.

  • Implementation of Posix Thread class in c++ for solaris system

    Hello Everyone,
    Please help me with information regarding how to implement Posix Thread Class in c++ for Solaris 5.8 system.
    if available Please let me know any Open Source Posix Threads C++ built-in library available for Solaris System.
    Thanks in Advance.
    Thanks & Regards,
    Vasu

    Posix threads are available on Solaris, and can be used directly in C or C++ programs. Include the header <pthread.h> to get access to the types, constants, and functions. Compile with the option
    -mt
    on every command line, and link with the options
    -mt -lpthread
    If you want to create a class to provide a different sort of interface to phreads you can do so by building on the <pthread.h> functionality.

  • Yield() of Thread Class

    hi friends
    Any one here who can explain me yield() of Thread Class.
    how i can use it in our program pls send any example of yield().

    Any one here who can explain me yield() of Thread
    Class.http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#yield()
    The API can.

  • A question about the Thread class

    the code below are two way of invoke a thread to run:
    A:
    public class Test {
    public static void main(String args[]) {
         Thread myThread = new Thread(){
              public void run(){
                   System.out.println("in myThread! \n");
                   System.out.println(Thread.currentThread());
         Thread th = new Thread(myThread,"new Thread");
         th.start();
    B:
    public class Test {
    public static void main(String args[]) {
         Thread myThread = new Thread(){
              public void run(){
                   System.out.println("in myThread! \n");
                   System.out.println(Thread.currentThread());
         myThread.start();
    i have read many free software's source code, and find many people would like to implement it like A instead of B
    so my question is why A is better than B.
    thanks!!

    A is actually using the constructor which accepts a Runnable. In your case, since you are overriding only run(), you could have simply implemented the Runnable and created the thread th. However, in this model you are using a Runnable you are actually separating the task from the Thread. In B, thread is actually the task which couples them tightly. Therefore, from design point of view, A is recommended with Runnable rather than a Thread unless you have specific reasons to do that.

Maybe you are looking for

  • JBO-33035: Row currency has changed since the user interface was rendered

    First - Yes I have read a number of the postings regarding this error - HOWEVER - there seems to be a 'rather' serious side effect that I need to get fixed. Am dropping on a a UIX datapage a datacontrol VO component as a Search Form. I have added Del

  • Multiple views of same document

    Is it possible in Pages to look at two different views of the same document? In Microsoft Word there is Split Screen which allows this. It is very useful for copying and pasting within a long document. I have not been able to find a way to do this wi

  • AP 1200 and authentication

    I have an AP configured with WDS and authenticate via a radius server. I notice that when i enable a user they are asked for a login but if they drop the connection or even shut the machine and go to log back in, they are NOT prompted for their login

  • AIR app (HTML) not responding after alert or confirm

    This issue won't occur when using adl for debugging, but after building the package and install, even an one-alert application will have this issue. I accidentally tested another app (3.1) I wrote a long time ago, and found the same thing... After sh

  • Next arrow buttons not functioning

    Hi All, I have report where we use hierarchy column, when i expand the + sign in the report, it shows as - but only 25 values are visible, now when i press on next arrow symbol, its not working. I am using conditions in the section of the dashboard T