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.

Similar Messages

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

  • 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

  • HttpServlet implements Runnable thread issue

    Hi,
    I have a servlet that implements Runnable. In web.xml I have set this servlet to load-on-start=1. In the init method of the servlet I have a thread that starts and basically runs forever. Now I am facing some issues and am not able to figure out what exactly is going on. I see exceptions in the log file and then my servlet stops. I have catch block all over but somehow whenever some exception occurs my Thread just stops and the servlet stops too I have to manually invoke the servlet so the Thread to start over again. Here is a code snippet. Now if any error occurs in insert() method somehow Thread just stops even though I am catching an exception. This servlet is not called from anywhere it just loads as soon as the app is deployed and then the thread keeps running and in my insert method I am reading some files and inserting into the database. How can stop the thread from being stopping and where at the top level I can add catch block to exactly print the error even though I am catching all the exceptions in the code itself. How can I keep my thread alive even after any exceptions.
    public class InsertData extends HttpServlet implements Runnable {
        Thread thread;
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            thread = new Thread(this);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.start();
        public void run() {      
            while (true) {                     
               insert();
               try {
                thread.sleep(10000);
              catch (InterruptedException ignored) { ; }
        private insert()
         try{
         catch(Exception exception)
        }Thanks

    Hi,
    After more debugging it turned out all the exceptions are handled correctly but some how after some time the thread just stops running in the servlet and even after invoking the servlet manually it doesn't start. Now asThread may take arround couple of minutes to finish but I am starting a new run every 1 minute which may lead to several Threads running a one particular time and as the time goes on thread increase also. So wondering if there's any limit on number of Threads to run at one particular time or is the Application Server removing any of these as in the code I don't see anything and no errors in the logs either.
    Is there a way to find out if a servlet is loaded. As in the Application Server control I do see a servlet loaded but I don't see any of the Thread running that calls the insert method.
    Also is it a good idea to have a Thread start in the init method that runs forever. Any other approach I can take. Writing a windows service or a cron job can be one but it's not in the scope. Other option I though of was using JMS and thru MDB I manually invoke the servlet and so I don't have to use Threads.
    Is there any other approach I can have by using servlet itself. Basically I want to call my servlet every lets say 30 minutes automatically.
    Thanks

  • Naming a thread that is created implementing Runnable

    How could I name a thread that I create using Runnable Interface?
    public class Test {
         * @param args the command line arguments
        public static void main(String[] args) {
            TestRunnable tr = new TestRunnable();
            /* running thread */
            new Thread(tr).start();//THREAD 3
    public class TestRunnable implements Runnable {
        public void run() {
            for(int y = 1; y < 1000; y++) {
                System.out.println("3333333333333333333333333333333333333333 " + Thread.currentThread() );
    }

    well, I'm just experimenting; learning about Threads. As you can see I
    was able to name the other two threads, I was just curious how you would do it,
    using the Runnable Interface, seeing as those two naming options I used don't
    seem to be an option for it. I may be misunderstanding your reply...
        public static void main(String[] args) {//thread 0
            FrameThread ft = new FrameThread();//extends Thread
            ft.setName("ft");
            Thread td = new Thread("td") {
                @Override
                public void run() {
                    for(int a = 1; a < 1000; a++) {
                        System.out.println("1111111111111111111111111111111111111111 " + Thread.currentThread() );
            TestRunnable tr = new TestRunnable();//class implements Runnable
            /* running threads */
            td.start();//THREAD 1
            ft.start();//THREAD 2
            new Thread(tr).start();//THREAD 3
    }I'm naming them so when I use : Thread.currentThread() the return slot has the name I provide.
    Edited by: rico16135 on May 3, 2008 3:14 PM
    Edited by: rico16135 on May 3, 2008 3:17 PM

  • 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();

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

  • The Thread which won't let go...

    I posted very late last night and those who responded were a big help. Still, even though I changed my code I'm worked my way right around into a big circle and the exact same stopping point. Here is some sample code to try to simplify my complication.
    I'm attempting to complete an assignment (due in a few hours) lol... which is supposed to be an "application" not an "applet". It's a lesson in multi-threading. Supposidly there is a main thread which drives everything, several processing threads and a thread which prompts for input. I've got the Thread which prompts for input working just fine as well as the others. However, whenever one of the processing threads begins to process the data, I get no further DOS prompt from my input object until that Thread has completed. I'm going nuts trying to figure out how not to have this happen.
    I'll make an attempt at a simplified version of what's happening below:
    class mainThread impliments Runnable(){
        public void run(){
            while(true){
               //call inputThread object
               dataprocessor();
               //call processorThread object
        public void dataProcessor(){
            //processes data & calls on other methods & objects
            //to help
    class processorThread impliments Runnable(){
    //several of these objects are created to process data
    class InputThread impliments Runnable(){
    //has two methods as given to us by instructor
        public String method1(){
            //involks prompt requesting Strings or characters from user
            //  returns String
        public int method2(){
            //involks prompt requesting integer from user
            //  returns int
    }The problem is when processorThread object is called, everything stops and waits for it to complete. Help!!

    A thread has 3 elements;-
    - start()
    - run()
    - stop()
    controlled by boolean values if(myInt==myCondition){
      myThread.stop();   // method is depricated as it may not stop 'cleanly' and thrfr = memory prob's
      nowPutTheCatOut - etc
    // Better method;-
    public void start() {
    if(myCondition=false){
      myThread.run();
    // X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*Hope that helps

  • How to add timeout for threads which are running  using ThreadPoolExecutor

    I am trying change my existing functionality with ThreadPoolExecutor. I was unable to achieve fully.
    Here is my issue.
    I was creating multiple threads for independent DB update operations. And was calling join with time value on the each thread, for any reason if the db update hangs so that thread should die.
    Now am trying use a nice ThreadPoolExecutor so that it can run and queue the threads nicely. But how do I create the timeout values for the threads which are in the ThreadPool. For any reason if the thread hangs then timeout will take care of killing the thread. When we use execute method submit the runnable task its not guaranteed that thread will run immediately. So when the executor will execute the submitted task is not know.
    Probably I might be wrong some where.
    Thanks.

    Future task = threadPoolExecutor.submit(...);
    //this will block until it finishes or times out.
    task.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);

  • Have downloaded new Lightroom 5.4 from CC. When trying to launch am getting following error message and then Lightroom crashes: "an error occurred when attempting to change modules". Can't find a thread which relates to this error message.

    Have downloaded new Lightroom 5.4 from CC. When trying to launch am getting following error message and then Lightroom crashes: "an error occurred when attempting to change modules". Can't find a thread which relates to this error message.

    Hi 99jon,
    Many thanks for that. Had been going through this list yesterday and now again today:
    Ref  Solution 1: Lightroom is at its latest update
    Ref  Solution 2: It's interesting how I cannot find the Preferences file anywhere on my mac. (new mac pro, OS 10/9.2) . . .
    Ref  Solution 3: Lightroom doesn't allow me to do anything after the error message appears
    Ref  Solution 4: don't have any Nik Software plug-ins
    Ref  Solution 5: checked permissions and changed all to "Read & Write" - makes no difference
    Ref  Solution 6: I don't have a different user account on my mac.
    Not sure what else to do.

  • CAn we make a thread which is very useful as a Sticky thread

    Hi all,
    I have a thread which is very help ful to provide the basic idea of OO workflows can we make it as Sticky thread
    New blog available....
    Regards
    Pavan
    Moved to the correct forum
    Edited by: Hilit Fisch on Apr 8, 2009 9:06 AM

    Hi Pavan,
    Yes, That would be fine.
    Regards,
    Surjith

  • Qestion for implementing Runnable

    HI,
    I have a function which executes multiple methods and store the result from those methods in List<Stirng> before the last methods executes I need to insert these List<String> values in a database with my dao object.
    I was wondering if I do the following:
    new Thread(new myInsertWorker()).start();
    executeMyFunction();
    Would I improve the performance on my program since it is very important for this last function to be fast.
    My question is if I insert the strings as a separate thread how do I need to write the thread to be as simple as possible and not cause any performance issues?

    Here is my code, I am new to concurrent programming, therefore I move slowly :) and check my code with someone else to prevent issues I am not aware of.
    Can I improve this simple piece of code to make sure if it does fail or hangs my application will not be affected?
    Thank you
    public class LogMessageWorker implements Runnable {
        List<LogMessage>_messages = new LinkedList();
        LogMessageDAO _logMessageDAO=null;
        public LogMessageWorker(LogMessageDAO logMessageDAO, List<LogMessage> messages){
            this._messages = messages;
            this._logMessageDAO = logMessageDAO;
        public LogMessageWorker(LogMessageDAO logMessageDAO, LogMessage message){
            this._messages.add(message);
            this._logMessageDAO = logMessageDAO;
        public void run() {
            try{
                _logMessageDAO.add(_messages);
            }catch(Exception e){
                e.printStackTrace();
    }This is how I call it:
    try {
                Thread logMsgThread = new Thread(new LogMessageWorker(logMessageDAO, logMessages));
                //logMsgThread.setPriority(Thread.MIN_PRIORITY);
                logMsgThread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }Edited by: kminev on Dec 3, 2009 2:06 PM

  • Reflect the class that implements Runnable

    Hi,
    I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
    I am wondering is it possible at all to start a new thread on a reflected class?
    thanks in advance.
    {              Class refClass = Class.forName(className);
    String methodName = "start";
    Class[] types = new Class[1];
    types[0] = Class.forName("java.util.HashMap");
    Constructor cons = refClass.getConstructor(types);
    Object[] params = new Object[5];
    params[0] = new HashMap();
    Method libMethod = refClass.getMethod(methodName, null);
    libMethod.invoke(objType, null); }

    Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
    In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
    But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
    Runnable r = // some object which implements Runnable
    new Thread(r).start();Not what you wanted? Go ahead and clarify then.

  • Panel implements Runnable?

    Is it possible to implement Runnable in a Frame panel?
    I have an Applet Frame for drawing polylines and I want to add a scrolling text panel at the bottom of the frame.
    I have a horizontal text applet already, however, when I try to add it's functionality to the frame's panel I get a nullpointerexception error.
    Can anybody help,
    thanks Aidan

    This is the original applet that I used for scrolling text.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextPanel extends Applet implements Runnable
    private Thread textthread;
    boolean FirstPass;
    private String Text;
    private int S;
    private Color bgC;
    private Color textC;
    private Color tempC;     
    private int xPos;
    private int yPos;
    private int textWidth;
    private int aWide;
    private int aHigh;
    private String fontName;
    private Font F;
    private Image iBuff;
    private Graphics gBuff;
    private Image iTheText;
    private Graphics gTheText;
    private boolean LoadPause;
    private int RP;
    private int VB;
    public TextPanel()
    textthread= null;
    FirstPass = true;
    Text = " Scrolling Text. ";          
    S = 40;
    xPos = 1;
    yPos = 0;
    textWidth = 0;
    aWide = 0;
    aHigh = 0;
    bgC = new Color(255, 255, 255);          
    textC = new Color(0, 0, 0);
    tempC = textC;               
    fontName = "TimesRoman";
    LoadPause = true;
    RP = 1000;
    VB = 0;
    iBuff = null;
    gBuff = null;
    public void init()
    aWide = 600;
    aHigh = 16;
    prepMessage();
    makeText();
    if (iBuff == null)
    iBuff = createImage(aWide, aHigh);
    gBuff = iBuff.getGraphics();
    public void prepMessage()
    FontMetrics fontmetrics = null;
    F = new Font(fontName, Font.PLAIN, 16);
    fontmetrics = getFontMetrics(F);
    textWidth = fontmetrics.stringWidth(Text);
    int j = fontmetrics.getAscent();
    yPos = aHigh - fontmetrics.getMaxDescent() - fontmetrics.getMaxDescent() / 3;
    yPos = yPos + VB;
    public void makeText()
    iTheText = createImage(textWidth, aHigh);
    gTheText = iTheText.getGraphics();
    gTheText.setColor(bgC);          
    gTheText.fillRect(0, 0, textWidth, aHigh);
    gTheText.setColor(tempC);          
    gTheText.setFont(F);
    if(!FirstPass)
    gTheText.drawString(Text, 0, yPos);
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    if(++xPos > textWidth)
    xPos = 1;
    int i = xPos * -1;
    do
    if(!FirstPass)
    gBuff.drawImage(iTheText, i, 0, this);
    if(FirstPass)
    gBuff.drawImage(iTheText, 0, 0, this);
    i = 0;
    i += textWidth;
    } while(i < aWide);
    g.drawImage(iBuff, 0, 0, this);
    public void start()
    if(textthread== null)
    textthread= new Thread(this);
    textthread.start();
    public void stop()
    if(textthread!= null)
    textthread= null;
    public void run()
    if(FirstPass)
    FirstPass = false;
         makeText();
         if (!FirstPass)
         do
    try
    repaint();
    if(LoadPause)
    try
    TextPanel _tmp = this;
    Thread.sleep(RP);
    catch(InterruptedException interruptedexception) { }
    LoadPause = false;
    TextPanel _tmp1 = this;
    Thread.sleep(S);
    catch(InterruptedException interruptedexception1)
    stop();
         }while(true);
         else
         return;
    I was hoping to have a class
    Where the applet created a frame with e.g. a canvas panel and a textscrolling panel i.e. by changing the init() method to include the following.
    public void init()
    Frame frame = new Frame("Text scroller");
    frame.setSize(600, 100);
    Panel panel = new Panel();
    panel.setSize(aWide, aHigh);
    TextPanel textpanel = new TextPanel();
    panel.add(textpanel);
    frame.add(panel);
    textpanel.start();
    frame.setVisible(true);
    The text scroller runs in the html page and the frame is empty. is it possible to add the scrolling text to the frame.

Maybe you are looking for

  • Transferring Itunes Library to External HD  - BUT not so straighforward

    Oh dear, here I am again asking q's about this thing again. Wish it was more straightforward and I really appreciate any help. Yes, I've been searching for a solution but all the advice i find online doesnt seem to specifically fit my situation - and

  • Installing Apache on Fedora 2

    During Apache installation on Fedora 2 from Oracle DB10g Companion CD I recieved message : Error in invoking target 'install' of makefile /u01/...../ins_sqlplus.mk. In error log I have read: /usr/lib/gcc-lib/i386-redhat-linux/3.3.3/libgcc_s.so: undef

  • Problem with from_TZ function

    I am getting different results for the below query when DST is about to end: same on 1 day before and on Next Day after DST Ends but different on DST Ending Day. On 24th Oct 2009 12pm afternoon, when DST is still there: sdp1:/#date Sat Oct 24 12:01:0

  • Here's a strange problem in Photoshop CS5 Extended....

    I finally got Photoshop CS5 Extended to open images new and existing by rolling back my video drivers.... Awesome, great, fantastic, euphoria ensues...... until I type some text and nothing appears..... Hmm... That's strange... I thought maybe it mig

  • Hi. Can use events to look out for input switches from any DAQ board?

    I tried using events to detect signals from input switches Advantech PCL-8181L, but it seems no response. I have read an article about the events that user controls can trigger and some external IO cannot. Is there any one know how I can get the prog