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

Similar Messages

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

  • 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

  • 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

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

  • 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

  • Extends Thread versus Implements Runnable... difference?

    I've seen them both used and to the naked eye it seems to be pretty much the same (besides the execution).
    Can anyone tell me the major differences between the two methods of multi-threading and how/if one is better?
    Do you ever make a deliberate choice to use Extends over Implements (or vice versa) for a specific task?

    For the record, I've normally used extends Thread, and
    seeing the light that in doing that, I can only extend
    one class, I'm looking into the alternative.
    Are...
    Thread t1 = new Thread(new myRunnableThread());
    Thread t2 = new Thread(new myRunnableThread());
    t1.start();
    t2.start()
    and...
    MyExtendedThread t1 = new MyExtendedThread();
    MyExtendedThread t2 = new MyExtendedThread();
    t1.start();
    t2.start();
    equivalent?
    equivalent meaning that they are equally fast? I'd say no, because in the first example you are creating a thread and a runnable, in the second you are only creating a thread.
    >
    Additionally, consider -
    public class myExtendedThread extends Thread {
    ServerSocket ServiceConnectSocket = new
    ServerSocket(4000);
    NotificationListener mainThread;
    public myExtendedThread(NotificationListener
    _mainThread) {
    mainThread = _mainThread;
    public void run()  {
          while(true)
                 if (ServiceConnectSocket != null)
                     return;
                 try
                     Thread.sleep(5000);
    ServiceConnectSocket = new
    ectSocket = new Socket(host, port);
                     ServiceConnectSocket.close();
                     mainThread.serviceReady();
                 catch (Exception e)
    >
    This thread basically tries to connect to a socket,
    and when it does, it closes the socket it made,
    notifies another thread (passed in at the constructor)
    and returns.
    My question is on what happens when Threads return.
    When this thread returns... what happens exactly?
    What if mainThread.serviceReady restarted that
    t thread? Would it start a NEW thread or just re-run
    the run() of the old one?
    Once a thread returns, how long before Garbage
    Collection will free up the memory it used?
    When the run method returns, the thread is dead. It is not reused automatically. You have to implement some type of thread reuse like my code above.
    I would assume that the normal GC rules apply. Each JVM can decide to cleanup the thread whenever it feels like it.

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

  • Access denied when I implement Runnable?

    Wow.. I've been trying to isolate this problem for ages. I just got down to it by first making an applet that displays a static image, which works fine, and then using a run() method to animate it with just one more frame. When I use the run method it churns out a lot of rubbish in the DOS window, which ends
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:484)
    I don't know what's going on here... Is there a problem with my JDK, because I've installed it twice already? It compiles fine, with just one mention that I've overridden a method, namely paint, which is empty anyway. Help!

    Without the code and the exact exception, I can't be entirely sure of the problem, however I can guess. If you are implementing Runnable, you should not be calling your run method directly. You mentioned that this is an applet, so you should write your start method as:
    public void start(){
      (new Thread( this ) ).start();
    }Which will create and start a new thread whose run method (the code it will be executing) is what you have written in your run method.

  • 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

  • Difference between extends and implements

    hi
    i am new to java. i need to know the difference between extends class implement class.
    can anybody explain in simple words? i am new too oops concept also?
    what are the conditions to use extends class, implement and interface?
    class b extends a implements c
    i know class a is a super class and class b is a sub class.
    if class b extends class a means how should be the class a, what about the methods?
    and class a implements class c means what should be the conditions?
    i searched in Internet but the explanation is not very to me.can body explain me please?
    thank you

    sarcasteak wrote:
    Your class can implement an interface, which means it must use the methods defined in the interface.No, it doesn't need to use them. It needs to implement them. Or be declared abstract.
    Note that the methods in the interface are empty,No, they're not. They're abstract.
    // empty method
    void foo() {}
    // abstract method
    abstract void foo();(The abstract keyword is optional for interface methods, since they're all abstract.
    and you have to define what they do in your class that implements the interface.Just like they have to for abstract methods in a class you extend, if the child class is not declared abstract.
    There really isn't any difference between "extends" and "implements." There is no situation where you can choose. Any case where one is legal, only that one is legal. They could just as easily be a single keyword.
    Presumably the OP's real question is, "When do I use a class for a supertype vs. using an interface for a supertype?" The answer to that, of course, is:
    Use a class when at least some of the methods have valid default implementations. Use an interface when that is not the case. And of course the two are not mutually exclusive. It's quite common to do both.
    At the end of the day, an interface is really nothing more than a class that has no non-final or non-static member variables and whose instance methods are all abstract, and from which you can multiply inherit.
    Edited by: jverd on Feb 4, 2010 1:56 PM

  • 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

  • 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

  • Use extends and implements or not?

    What is considered a better way of implementing classes? with the use of extends and/or implements or not?
    ex:
    public class TabPanel extends JPanel implements ActionListeneror have it return the needed Type
    ex:
    public class TabPanel implements ActionListener
    public JPanel TabPanel()
    JPanel jp = new JPanel();
    jp.add(new JLabel("Test"));
    return jp;
    }

    To extend or not to extend, that is a question. Defenitely, you must subclass when you need to override some method. You want to subclass to reuse the customized class. You want to implement an interface when you need a class implementing it.
    Regarding your example:
    public class TabPanel implements ActionListener {
         public JPanel TabPanel() {
              JPanel jp = new JPanel();
              jp.add(new JLabel("Test"));
              return jp;
    }Are you sure it will work? IMO, you do not have to specify result type and must not return anything in the constructors. Why to bother with TabPanel class? If you like to hide the scope, use {} braces in the code.
    JPanel panel = new JPanel();
    jp.add(new JLabel("Test"));
    public class NonAnanymousListener implements ActionListener {

Maybe you are looking for