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.

Similar Messages

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

  • 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(){
    }

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

  • Threads: implement runnable or extend Thread.  Which is better?

    I want to know which way is better, as I want to do some work in threads.
    Thanks,
    Virum

    I want to know which way is better, as I want to do
    some work in threads.
    Thanks,
    VirumOne reason for implementing runnable can be that java doesnot allow multiple inheritance so by implementing runnable you can, at the same time, extend another class.
    Another reason though not recommended and not good programming practice is that although you cannot restart a dead thread, if you use runnables, you can submit the old runnable instance to a new thread, thus practically starting a thread more than once.

  • Implements Runnable vs extends Thread

    Hello,
    Why do we call method run() in a Runnable class a thread? (at least my textbook implies such concept)
    If thread is an independent process, which runs on its own - then it's not about Runnable.run().
    public class RunnableThread implements Runnable
        public void run()
            for (int i=0; i<100000; i++)
                if (i%50000 == 0)
                System.out.print(i+" ");
        public static void main (String args[])
            System.out.println("Before thread");
            new RunnableThread().run();
            System.out.println("Thread started");// this line is executed only after
            // run() returns, not like with "true" threads, where execution course          
            //doesn't wait for start() to return
    }Or should I consider run() a regular (non-thread) method needed only to bypass extends restrictions?

    Why do we call method run() in a Runnable class a
    thread? We don't.
    (at least my textbook implies such concept)Perhaps you could post what your textbook says, and we can decipher it for you.
    If thread is an independent process, which runs
    on its own - then it's not about Runnable.run().Don't know what you mean by it being "about" Runnable.run()?
    Runnable.run is the method that gets executed when a thread is started.
    Or should I consider run() a regular (non-thread)
    method needed run() is a regular method. It happens to be one that is declared in the Runnable interface and is called by an executing thread. In your example code, you use just call run as you would any other method, so it acts just like any other method. To run it in a separate thread, you should call start() on the thread, not run(). The Thread object will then enter the waiting state and will call run() itself at the appropriate time.

  • Implementation of Runnable in a Bean class

    Hi All,
    Can a Session bean class implement Runnable? Can the business methods of Component Interface be run on different threads?
    If yes, then how do I start the thread when I know that it is actually the EJBObject that is inturn calling the method on the bean instance?
    Please answer my query.

    You might want to consider using the EJB Timer Service if you have time-based or asynchronous tasks you need to perform. See Chapter 22 of the Java EE 5 tutorial :
    http://java.sun.com/javaee/5/docs/tutorial/doc/
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Expose Object Oriented Service code as Web Services?

    Hello All, I would appreciate for your insight on this matter! Web Services are basically RPC (Procedure Oriented) over Soap. Each service invocation by a client results a procedure execution on the server side (In many case, a service class may need

  • Flat-File MA accented character conversion

    Hello, we are using FIM 2010 R2 SP1 (4.1.3599) with a flat file MA to import/sync a csv flat-file generated by a HR system. We are using UTF-8 code page. The HR system has many international people in it, so there are many accented or diacritic chara

  • Lotus Notes Portlet

    I have been having similar problems as forum messages # 520072 & 524480 (ref. below). my only difference is that in the apache error log I get the following: java.net.MalformedURLException: unknown protocol: https at java.lang.Throwable.fillInStackTr

  • Error in connecting to BW System in Enterprise Portal

    The error given is    "Logon Balancing:parser error in '/M/G/3220/'  "

  • Wldeploy ant task hangs at [ServerConnectionImpl.close():332] : Closing DM

    Hi All I am trying to deploy\undeploy a WAR file on weblogic server 10.3.5 using ANT wldeploy task, but no matter what i do it always hangs at the below and doesn't complete (although deployment and undeployment is successful) [wldeploy] [BasicOperat