Runnable interface

How start() calls the run(). How run() is defined in the Thread class. How our program's(which implements Runnable) implementation of run() is called while using a Thread object reference variable??

The run() method in Thread does nothing.
Each Thread object is associated with a Runnable object, if you don't supply one then it uses itself (Thread implements Runnable). It's best always to supply one for a number of reasons. (You can override the run() method of Thread but that's not good practice).
When you call start() a new execution context is generated to execute the run() method of the Runnable. That means a new stack for local variables, and a new execution point.
The old execution context then continues as normal.

Similar Messages

  • What is the diffrence between My Runnable Interface and Java Runnable

    Hi folks
    all we know that interfaces in java just a decleration for methods and variables.
    so my Question is why when i create an interface its name is "Runnable" and i declared a method called "run" inside it.then when i implements this interface with any class don't do the thread operation but when i implement the java.lang.Runnable the thread is going fine.
    so what is the diffrence between My Runnable Interface and Java Runnable?
    thnx

    Hi folks
    all we know that interfaces in java just a decleration
    for methods and variables.
    so my Question is why when i create an interface its
    name is "Runnable" and i declared a method called
    "run" inside it.then when i implements this interface
    with any class don't do the thread operation but when
    i implement the java.lang.Runnable the thread is going
    fine.
    so what is the diffrence between My Runnable Interface
    and Java Runnable?
    thnxClasses and interfaces are not identified by just their "name", like Runnable. The actual "name" the compiler uses is java.lang.Runnable. So even if you duplicate the Runnable interface in your own package, it's not the same as far as the compiler is concerned, because it's in a different package.
    Try importing both java.util.* and java.awt.* (which both have a class or interface named List), and then try to compile List myList = new ArrayList();

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

  • Runnable interface declaration

    Hello,
    Although the function run() is inside the public interface Runnable. its once again declared as abstract. Can i get to know the reason for this ?
    Thanks in advance.

    Abstract and public have nothing to do with each other.
    Every method in every interface is implicitly public and abstract. They can be declared that way or not, but if they are, it's redundant. Some programmers might choose to explicitly declare them public and/or abstract to make it obvious, but it's not necessary and it has no effect.

  • 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

  • Need Clarification reg Runnable interface

    Hi,
    I want to know how can we create a instance of the interface Runnable. I have seen the code running with " new Runnable" in swings. How can we can instantiate the interface. pls clarify if any of you know.
    Thanks,
    Guhan.

    Thanks you very much Hacker.
    _Guhan.                                                                                                                                                                                                                           

  • Have Trouble understanding the runnable interface

    Hi
    I am new to java programming. I have trouble understanding threading concepts.When I run the below code,Thread3 runs first. I need a small clarification here- I created two thread objects
    Thread thread1=new Thread(new RunnableThread(),"thread1");
    Thread thread2=new Thread(new RunnableThread(),"thread2");
    As soon as I create these objects -Will the constructor with the string argument in the "RunnableThread" class gets invoked. If so why doesn't System.out.println(runner.getName()); get invoked for the above objects. what is the sequence of execution for the below program.
    /*************CODE****************************/
    class RunnableThread implements Runnable
         Thread runner;
         public RunnableThread()
         public RunnableThread(String threadName)
              runner=new Thread(this,threadName);          //Create a new Thread.
              System.out.println(runner.getName());
              runner.start();          //Start Thread
         public void run()
              //Display info about this particular Thread
              System.out.println(Thread.currentThread());
    public class RunnableExample
         public static void main(String argv[])
              Thread thread1=new Thread(new RunnableThread(),"thread1");
              Thread thread2=new Thread(new RunnableThread(),"thread2");
              RunnableThread thread3=new RunnableThread("thread3");
              //start the threads
              thread1.start();
              thread2.start();
              try
                   //delay for one second
                   Thread.currentThread().sleep(1000);
              catch (InterruptedException e)
              //Display info about the main thread
              System.out.println(Thread.currentThread());
    }

    srinivasaditya wrote:
    Hi
    I am new to java programming. I have trouble understanding threading concepts.I'd consider it to be an advanced area.
    When I run the below code,Thread3 runs first. I need a small clarification here- I created two thread objects
    Thread thread1=new Thread(new RunnableThread(),"thread1");
    Thread thread2=new Thread(new RunnableThread(),"thread2");No, this is wrong. You don't need your RunnableThread. Runnable and Thread are enough. Your wrapper offers nothing of value.
    >
    As soon as I create these objects -Will the constructor with the string argument in the "RunnableThread" class gets invoked. If so why doesn't System.out.println(runner.getName()); get invoked for the above objects. what is the sequence of execution for the below program.did you run it and see? Whatever happens, that's the truth.
    %

  • Using Runnable Interface

    Hi-I'm using the following code to bring up an application(Like a text editor or Internet Explorer) with a file (html or text) as the argument.
    public void run()
        String app = "C:/Program Files/EditPlus 2/editplus.exe";
         String[] callAndArgs = { app, filename };
        String call = app;
        Process child =null;
        try {
        Runtime rt = Runtime.getRuntime();
        if(filename==null) {
        child = rt.exec(call);
        else{
        child = rt.exec(callAndArgs);
        child.waitFor();
        System.out.println("Process exit code is: " + child.exitValue());
        catch(IOException x) {
        System.err.println("IOException starting process!");
        catch(InterruptedException x) {
        System.err.println("Interrupted waiting for process!");
    }This works fine, the passed in file (filename) shows up in EditPlus no problem.
    My question is: Can you bring up the application (EditPlus) inside of a JPanel for example,
    instead of it's own window? Or force it's window into a JPanel?
    Appreciate any help..
    -Reg

    Except for in a very few cases you can't do this
    What are the cases I speak of? Search the web for the JDIC project and poi

  • Problems with interface runnable

    Hi everyone !!,
    I have been developing an application with JDK 1.5.0_06 and applications server Apache Tomcat 1.4.31. It is a multithreaded application which uses a class that implements a runnable interface.
    At the moment, this application must be compiled and executed in another machine with JDK 1.5.0_05. The problem is that when an instance of the interface Runnable is called and its method .start() executed , the instance isnt created and the method run doesn't start.
    I hope you understand what I mean. If you dont , please, ask me.
    Any idea? Any help? I have no idea why this is happening? any problem with the JDK? the applications server?
    Thanks in advance, Mar�a

    problem is that when an instance of the interface
    Runnable is called and its method .start() executed ,
    the instance isnt created and the method run doesn't
    start.
    I hope you understand what I mean. If you dont ,
    please, ask me.
    I don't understand.
    Runnable does not have a start() method.
    What do you mean "the instance isn't created"? If you create an instance of something, it's created. If you don't, it's not.
    If you call a Thread's start() method, that Thread's Runnable's run() method will be executed in a new thread of execution. If you don't, it won't.

  • Using empty interface -- is there a better way to do this?

    Hi,
    I have a set of classes in different projects that I'd like to be referenced together, although they have different methods depending on which project they're from. To do so, I've created an empty interface for each of these classes to implement, so I can return a similar type and then cast it however I need to based on which project I'm using.
    However, I feel the approach of creating an empty interface just isn't the best way to do this. I've looked into annotations, but I don't think they can solve my problem. I don't think I'm being too clear here, so let me give a brief example:
    Here is one of the interfaces I use:
    public interface IceClient {
         public IceOperations operations();
    }Here is the empty interface:
    public interface IceOperations {
    }I have a method which will return a type of IceOperations:
         public static synchronized IceOperations getOperations(String clientName) {
              if (clientMap.containsKey(clientName)) {
                   IceClient client = clientMap.get(clientName);
                   return client.operations();
              } else {
                   System.out.println("No client of that name is currently running.");
                   return null;
         }This is all fine and dandy. I need to instantiate a new IceOperations object in my client code as such, where operations is of type IceOperations:
    operations = new DiagOperations();And finally return it like this, where client.operations() returns a type of IceOperations:
         public DiagOperations operations() {
              return (DiagOperations)client.operations();
         }Anyway I hope that wasn't too confusing. I cannot think of a different way to do this. Is there some way I can do this with annotations? The only other thing I can think of is just returning Object, but that seems ... icky.
    If I need to be clearer, please let me know.
    Thanks

    JoachimSauer wrote:
    I didn't understand them to be trick questions, but rather serious invitations to question and verify your assumptions.
    It might be the fact that every current implementation implements Runnable for some reason (possibly because it starts a Thread on its own). But it's entirely possible that you can produce a completely different implementation that doesn't need the Runnable interface and still be conformant.
    If every implementation of X needs to implement Runnable, then it could be a sign of a slight design smell. Could you give an example where you think it's necessary?Every implementation of my "X" interface is basically a class that acts as a communicator/listener of sorts until it's stopped by the user, similar to a server socket. Sometimes, it has to sit there and wait for events, in which case it obviously must be in its own Thread. Other times it doesn't have to do this; however if I do not start it in its own Thread, I will have to continually stop and restart the communication to invoke operations on the server, which is inefficient.

  • Trying to Understand Interfaces

    Hi all,
    As you might expect, I am new to JAVA. I have read the basics tutorial on interfaces and also the object oriented programming basics tutorial. I understand that you can't implement methods or variables in interfaces, etc. Here is what I am struggling with:
    A friend has written a class that uses the JNDI classes to query an LDAP service for person information and update database information. I notice that the query returns an object of type NamingEnumeration. But this is an interface, not a class. When he gets the items/elements from the Enumeration, he uses a (Attributes) to cast the results to their proper type.
    So, if I am writing a class and want to implement the NamingEnumeration interface over my class... and if I want to retrieve that class by its NamingEnumeration interface, rather than its actual class...how would I create a method that does this.
    My first attempt at creating this class went like this:
    public class DocumentEnumeration extends DocumentCollection implements NamingEnumeration
    If I called the .next method of my class, I would return a type Document. So far I don't know how to retrieve this DocumentEnumeration as a NamingEnumeration, and I received an error in my IDE about the constructor with arguments () is not visible. I did not understand this error either.
    Any help would be appreciated,
    Jeff

    DrClap's responses are all correct and to the point. Let me add a preface. Forget everything you've read, close your eyes and say "interfaces are dead simple!" about a hundred times. They are.
    An interface is a bundle of related capabilities. For example, I am a male homo sapiens (my class). I ski and play tennis - these are things I can do. As a Skier I have methods like buckleBoots(), getOnLift(), getOffLift() and skiDownHill(). All skiers implement these methods.
    TennisPlayers implement a different set of methods: serve(), volley() and so on. Some TennisPlayers may also implement Skier and some Skiers may implement TennisPlayer, but if an object of class LiftAttendant is going to call our getOnLift() method, it doesn't care about serve() or volley(). It knows that we have the handful of methods that concern LiftAttendants.
    Note that many different classes can implement an interface. Certainly some female homo sapiens implement Skier. I've also seen some apes and hot dogs implementing Skier.
    The Runnable interface defines just one method: public void run(). A Runnable is any class that claims it implements Runnable. If the class declaration claims that it implements Runnable, the compiler won't generate a .class file unless the class defines a public void run() method. When you pass a Runnable to a Thread, the Thread knows exactly one thing about the Runnable, that it has a public void run() method which the Thread can call after it is started. The Thread has no clue what it might be running, but because the object is a Runnable it can correctly call whatever.run().
    Why might a well-written method return an Interface type, not a class? Generality. The LiftAttendant need only know that an object has a getOnLift() method. So anything the implements Skier will be fine for the LiftAttendant.
    So an interface defines a set of methods (as few as one) that, taken together, constitute a capability. A class that implements these methods can claim to implement the interface, and other objects that care about that capability can say they work with Skier, or Runnable or whatever, so that they can handle lots of different things, not worrying about all the other things their Objects might implement or be.
    Very simple. Very powerful.

  • Overriding Interface methods via JNI

    Hello,
    How we can override Interface methods via JNI?
    For example:
    At HelloWorldSwing example:
    http://download.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java
    I've written anonymous Interface as:
    import javax.swing.*;       
    public class HelloWorldSwing1 {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Add the ubiquitous "Hello World" label.
            JLabel label = new JLabel("Hello World");
            frame.getContentPane().add(label);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        static Runnable runnableObject = new Runnable() {
             public void run() {
                  createAndShowGUI();              
       public static void main(String[] args) {
             //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(runnableObject);
    }via JNI functions(http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html) we cannot override Runnable Interface's run method? Can we?
    Only:
    RunnableClass's value isn't null with given example at below. FindClass finds the Runnable Interface.
    jclass RunnableClass;
    RunnableClass = (*env)->FindClass(env,"java/lang/Runnable");
      if( RunnableClass == NULL ) {
        printf("can't find class Runnable\n");
        exit (-1);
      }But How can we override Runnable class's run method?
    Thanks in Advance

    The only way you can override a method in Java is by defining a class that does so, either statically or as an anonymous inner class. You can't do either of those things in JNI. Ergo you cannot do what you are asking about.

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

  • Different output for each running (Thread & Runnable)

    When i run a program which extends Thread or implement Runnable interface, i get different output each time i run from either of the program. Why this can happen? Why the output from the program which extends Thread different from the output which implementing Runnable? i really can't figure out..can someone explain it to me?? thank you!!
    regards,
    san san

    Please be a little more explicit about what you're doing, what you expect to happen, and what you actually observe.
    Please post a short, concise, executable example of what you're trying to do. This does not have to be the actual code you are using. Write a small example that demonstrates your intent, and only that. Wrap the code in a class and give it a main method that runs it - if we can just copy and paste the code into a text file, compile it and run it without any changes, then we can be sure that we haven't made incorrect assumptions about how you are using it.
    Post your code between [code] and [/code] tags as described in Formatting Help on the message entry page. Cut and paste the code, rather than re-typing it (re-typing often introduces subtle errors that make your problem difficult to troubleshoot). Please preview your post when posting code.
    Please assume that we only have the core API. We have no idea what SomeCustomClass is, and neither does our collective compiler.
    If you have an error message, post the exact, complete error along with a full stack trace, if possible. Make sure you're not swallowing any Exceptions.

  • Different output for each running(Thread or Runnable)

    When i run a program which extends Thread or implement Runnable interface, i get different output each time i run from either of the program. Why this can happen? Why the output from the program which extends Thread different from the output which implementing Runnable? i really can't figure out..can someone explain it to me?? thank you!! Belows are the program im trying to run..
    <code>
    public class RunThreads
         public static void main (String [] args)
              SomeThread p1 = new SomeThread(1);
              p1.start();
              SomeThread p2 = new SomeThread(2);
              p2.start();
              SomeThread p3 = new SomeThread(3);
              p3.start();
    } //end class RunThreads
    public class SomeThread extends Thread
         int myID;
         SomeThread(int id)
              this.myID = id;
         public void run()
              int i;
              for(i=1;i<11;i++)
              System.out.println("Thread" + myID + ": " + i);
    } //end class SomeThread
    </code>
    <code>
    public class RunThreads2
         public static void main (String [] args)
              Thread p1 = new Thread(new SomeThread2(1));
              p1.start();
              Thread p2 = new Thread(new SomeThread2(2));
              p2.start();
              Thread p3 = new Thread(new SomeThread2(3));
              p3.start();
    } //end class RunThreads2
    public class SomeThread2 implements Runnable
         int myID;
         SomeThread2(int id)
              this.myID = id;
         public void run()
              int i;
              for(i=1;i<11;i++)
              System.out.println("Thread" + myID + ": " + i);
    } //end class SomeThread2
    </code>

    Umm, could you explain the differences in the output first?

Maybe you are looking for

  • Can't connect from PC laptop

    As did many others yesterday I had problems with Airport Extreme after the firmware update. I finally got that resolved, but now I can't connect wirelessly from my pc laptop. The network is visible and shows up as Automatic. Previously it came up as

  • Sldieshow pforlem on Verizon hosted sites.

    Revisiting a problem not reviewed since 2006 I wondered if anyone has found a workaround for the slideshow problem on verizon hosted websites. With earlier versions of iWeb it was found that the slide show did not work because the iWeb software had a

  • Error frm-40735 ora-01422

    Hi, I have two tables: dept( dept_name VARCHAR2(10), dept_info VARCHAR2(10), CONSTRAINT dept_pk PRIMARY KEY (dept_name) location( loc_name VARHCHAR2(10), loc_info VARCHAR2(10), dept_name VARCHAR2(10), CONSTRAINT loc_pk PRIMARY KEY (loc_name), CONSTRA

  • Anybody found a TWAIN plug-in for PS creative cloud?

    Has anybody found a TWAIN plug-in for PS creative cloud?

  • Firefox runs slow and stops for a bit

    I find that running flash games such as the ones through Facebook have a lag or the browser freezes up and I have to wait for it to finally go through after sometimes 20-30 seconds. Yet, Chrome and IE9 work without issue moving right through to what