Java Forum / General / July 2005
What is an interface?
billreyn@gmail.com - 05 Jul 2005 21:26 GMT Someone please help me out, I've looked at 50+ books on Interfaces. I understand contracts etc. But how on earth does an Interface method do something like start a thread running? eg:
class TryThreads implements Runnable { public void run() { for (int x = 1; x < 100; x++) { // runs a new thread } }
Above is MY implementation of the Interface method run() (its not exactly right, no matter), and it will run in its own thread. But I have not written anything to do with running a thread, so how does it 'know' to do this special task? (running a thread)??? All I do is my OWN implementation of run() which is just a 'for' loop. How does it 'know' to run it in its own thread?? According to every book I have read, an Interface only forces me to write my own method with the method name & params that is in the Interface. hat I understand, so how does it run a thread? Its not in my implementation.
Will some kind person explain whats going on in simple English that even I could understand.
Chris Smith - 05 Jul 2005 21:42 GMT > class TryThreads implements Runnable > { [quoted text clipped - 6 lines] > have not written anything to do with running a thread, so how does it > 'know' to do this special task? (running a thread)??? It doesn't. The Runnable interface means exactly what it says: something that can be run. For example, if I take your code and write:
TryThreads tt = new TryThreads(); tt.run();
This will *NOT* start a new thread. It will just run that for loop, in same thread that I used to call the method. There are also standard API interfaces that use Runnable instances to represent things that won't necessarily happen in a new Thread.
You're probably thinking of the following code:
TryThreads tt = new TryThreads(); Thread t = new Thread(tt); t.start();
This will start a new thread, and run the for loop in the new thread. However, the code to start a new thread isn't in your TryThreads class; it's in the standard API class java.lang.Thread. The standard API thread class just uses a Runnable instance to represent the code that the new thread will run.
Note that Runnable is really just a convention for encapsulating something that can be run. There are several other uses of Runnable besides starting a new Thread. For example, there is AWT's EventQueue.invokeLater, which schedules a task to be run at a later time in the AWT event dispatch thread rather than a new thread. An even better example is Java 1.5's java.util.concurrent.Executor, if you're working with that version.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
billreyn@gmail.com - 05 Jul 2005 21:50 GMT Thanks for the reply Chris, but I am still no nearer an understanding because I cannot see anything that Runnable has to do with threads whatsoever. The runnable Interface has in it is a naked run(*) method and nothing else in it. So why should it do anything at all with threads?
I am missing some basic point somewhere and have been for 3 years!
Daniel Dyer - 05 Jul 2005 22:22 GMT > Thanks for the reply Chris, but I am still no nearer an understanding > because I cannot see anything that Runnable has to do with threads [quoted text clipped - 3 lines] > > I am missing some basic point somewhere and have been for 3 years! That's because there is nothing in the Runnable interface that is connected in any way with threads. Runnable is just a way of describing some block of computation/piece of work that can be performed, it has nothing to do with threads. All it says is that any object that claims to implement Runnable will always have a method called run that will perform some unspecified work. If you call run whatever logic is in the run method gets executed and that's it. It really is as simple as it looks.
The Thread class however is more complicated. It depends on Runnable even though Runnable knows nothing of threads. All the magic involved in spawning threads is hidden away in the Thread class. The only reason threads use Runnable is because a thread needs be provided with some work to perform and that work is encapsulated in the run method of a Runnable object.
Dan.
 Signature Daniel Dyer http://www.dandyer.co.uk
billreyn@gmail.com - 05 Jul 2005 23:19 GMT I still can't see what 'Runnable' gets you if it has no connection to the Threads class, why use it at all? There must be some message passed for it to make any sense?
This program creates a new thread and start() calls run(). Why? There's no connection. Whats the Interface doing - is it that the Thread object looks for a method called run()? In which case why not just have a method called run() with no Runnable Interface, that should work too (but it doesn't)?
import java.io.*; class TryThreads implements Runnable { public void run() { for (int x = 1; x < 100; x++) { // runs a new thread called 'Fred' System.out.println("I am thread: " + Thread.currentThread().getName()); } } public void tester() { System.out.println("I am not thread Fred but I am thread " + Thread.currentThread().getName()); } public void tester2() { System.out.println("I am also not thread Fred but I am thread " + Thread.currentThread().getName()); } } class DriveThreads { public static void main(String [] args ) { TryThreads tr = new TryThreads(); Thread t = new Thread(tr); // t is a new thread called 'Fred' t.setName("Fred"); t.start(); // calls 'run' method in TryThreads class for (int x = 1; x < 100; x++) { System.out.println("I am an ordinary 'for' loop in thread " + Thread.currentThread().getName() ); } tr.tester(); tr.tester2(); } }
OUTPUT Creates a thread called Fred and the normal thread called main continues to run also.
Mike Schilling - 06 Jul 2005 00:12 GMT >I still can't see what 'Runnable' gets you if it has no connection to > the Threads class, why use it at all? There must be some message passed [quoted text clipped - 5 lines] > method called run() with no Runnable Interface, that should work too > (but it doesn't)? For one thing, requiring the interface allows a normal compile-time check that run() is defined. If C1 implements Runnable, it has a public method name Run() with no arguments.
Chris Head - 06 Jul 2005 07:06 GMT > I still can't see what 'Runnable' gets you if it has no connection to > the Threads class, why use it at all? There must be some message passed [quoted text clipped - 5 lines] > method called run() with no Runnable Interface, that should work too > (but it doesn't)? [snip]
Hi, Why use it? You say yourself in an earlier post that you understand the "contract" idea: this is EXACTLY what's going on here.
When we construct a new thread (an instance of java.lang.Thread), how do we tell it what code to run once it starts? In C, we would pass a pointer to a function to our thread library. In Java, there are no pointers to methods, so we use an instance of a class instead. The specification for java.lang.Thread says that the new thread will invoke run() on the given object. Thus, by defining run(), you are defining what work the thread will do. You ask, "why do we need the Runnable interface"? Here's why: imagine that the java.lang.Thread constructor accepted an Object instead of a Runnable. In this case, you could pass in an object whose class didn't contain a run() method. What should the thread do when you call start() now? Explode? Throw an exception? Throwing an exception would be the sensible thing to do. However, this leads to our next problem: the exception is thrown at runtime. The java.lang.Thread class must check, at runtime, whether or not your class contains a run() method. This takes a bit of CPU time, it takes a bit of time out of the Sun programmers' lives, and it also means you won't notice that your run() method is missing until runtime (you won't find out at compile time). In contrast, by using a Runnable, there's no way you can possibly pass in an object which doesn't contain a run() method. The presence of the method is absolutely guaranteed. If you misspell it an type Run() instead of run(), for example, you'll be informed of the fact by the compiler. You won't have to wait until your program runs. Better still, maybe the thread gets started only one in a million times. Do you want to have to start your program a million times to discover a spelling mistake? (before anyone jumps on me and says that you should be testing the thread's functionality anyway, I agree: without compile-time checking, you'd have to start your program a million times to find the spelling mistake, fix it, recompile, and then start it ANOTHER million times to check the function's behaviour)
Sorry for rambling. Anyway, it's just the contract idea. If a Thread is going to fulfil its contract to you and run code you specify in a separate thread, you must fulfil your contract to the Thread by providing the code to run in the proper format. That's a Runnable.
Chris
Dale King - 15 Jul 2005 05:23 GMT > I still can't see what 'Runnable' gets you if it has no connection to > the Threads class, why use it at all? There must be some message passed > for it to make any sense? > > This program creates a new thread and start() calls run(). Why? There's > no connection. Yes, there is a connection. That connection does not come from the Runnable interface itself. The connection is in this code:
> TryThreads tr = new TryThreads(); > Thread t = new Thread(tr); // t is a new thread called 'Fred' You created a new thread and "connected" it to the TtyThreads instance. The thread object you created saves the reference to the Runnable instance in a field of the thread object.
When you invoke start() it creates a new thread which then gets the reference to the Runnable instance and invokes its run method.
> Whats the Interface doing - is it that the Thread object > looks for a method called run()? In which case why not just have a > method called run() with no Runnable Interface, that should work too > (but it doesn't)? But there is no way in Java to reference a method except for reflection. If you want to point to something else that something else has to be an object.
Interfaces are somewhat like a function pointer, but it allows you to point to a whole set of functions not just one.
I could confuse the matter further by telling you that you can also subclass Thread and put your run method in the subclass. This only works because, in a very bad design decision on Sun's part, Thread itself implements Runnable and the no-arg constructor stores a reference to itself. I recommend against this approach however.
 Signature Dale King
Andrew McDonagh - 15 Jul 2005 19:52 GMT > Interfaces are somewhat like a function pointer, but it allows you to > point to a whole set of functions not just one. Interfaces are nothing like a function pointer.
They are a Type-ing mechanism, much like a C++ pure abstract class, only with greater restrictions with which they can contain.
Andrew
Mike Schilling - 15 Jul 2005 21:15 GMT >> Interfaces are somewhat like a function pointer, but it allows you to >> point to a whole set of functions not just one. [quoted text clipped - 3 lines] > They are a Type-ing mechanism, much like a C++ pure abstract class, only > with greater restrictions with which they can contain. An interface in Java is a contract to implement a set of method signatures, nothing more and nothing less.
Stefan Ram - 15 Jul 2005 21:29 GMT >An interface in Java is a contract to implement a set of method >signatures, nothing more and nothing less. It is a (reference type) specification, which might be used in a declaration, instanceof, or cast expression.
A contract is an act resulting from the corresponding declaration of two parties. What would correspond to such a declaration would not be the interface( specification), but the "implements" clause of a class declaration. This alone is not a declaration from two parties, but from a single party.
Then, a reference expression might be written, which has an interface type, which then indeed comes close to a kind of contract between a class and a client.
Andrew McDonagh - 15 Jul 2005 22:54 GMT >>>Interfaces are somewhat like a function pointer, but it allows you to >>>point to a whole set of functions not just one. [quoted text clipped - 6 lines] > An interface in Java is a contract to implement a set of method signatures, > nothing more and nothing less. I think you are taking a simplistic meaning from what is a woolly training wording of 'interfaces as contracts to implement' .
Yes, a class implementing an Interface is bound to either implement or mark as abstract the method signatures defined within the interface. However they are first and foremost a typing mechanism.
If it wasn't a type specification, how could we pass objects around as either their direct class type OR the interface they implement?
Mike Schilling - 16 Jul 2005 02:03 GMT >>>>Interfaces are somewhat like a function pointer, but it allows you to >>>>point to a whole set of functions not just one. [quoted text clipped - 16 lines] > If it wasn't a type specification, how could we pass objects around as > either their direct class type OR the interface they implement? Of course they're types; I didn't think that was in dispute.
But they're quite different from base classes. See my response to Tor for further explanation.
Tor Iver Wilhelmsen - 15 Jul 2005 23:41 GMT > An interface in Java is a contract to implement a set of method signatures, > nothing more and nothing less. Yes it is: It is also a part of the type system. Otherwise, having "empty" interfaces like Cloneable or Serializable would be pointless with your definition.
Mike Schilling - 16 Jul 2005 01:42 GMT >> An interface in Java is a contract to implement a set of method >> signatures, [quoted text clipped - 3 lines] > "empty" interfaces like Cloneable or Serializable would be pointless > with your definition. True, it's something you can reflect on as well; that is the only use of empty methods, to be able to say
if (o is Cloneable)
That's kind of a bastard use of interfaces; it would have been better to use attributes, if they'd been around at the time.
But an interface isn't the same as a C++ abstract base class; the methods that implement the interface are not marked as inherited from the interface in any way. Thus the problem that if you want to implement two interfaces that declare a method with a common signature but different semantics, you're screwed: there is no way to implement the two foo() methods differently. In C++, there is a solution to this problem, because base1::foo() and base2::foo() are different things with different identities (different offsets in the virtual table, if you want to talk implementation.)
Dale King - 16 Jul 2005 06:22 GMT >> Interfaces are somewhat like a function pointer, but it allows you to >> point to a whole set of functions not just one. [quoted text clipped - 3 lines] > They are a Type-ing mechanism, much like a C++ pure abstract class, only > with greater restrictions with which they can contain. They are something like the way you use function pointers in C. That is why I said "somewhat". Of course they aren't the same thing and I didn't say they were.
An interface gives you a way to point to an object that provides a set methods or functions (let's not get hung up on the terminology here) that you can call. A function pointer gives you a way to point to a single function that you can call. In that way they are "somewhat" like each other.
In most C threading API's you give it a function pointer to the code you want to run (and usually a parameter that is passed to point to some state information). With Java you give it a pointer to an instance of Runnable which has the pointer to the "function" and the state is contained in the instance.
From their use in this respect for specifying the code to run for a thread they are very similar.
 Signature Dale King
Will - 18 Jul 2005 16:16 GMT Yes Dale, thats interesting. The thread class behaves in this way. Once it gets a Runnable object then it calls the run() method (after start(). - Mimicking a delegate sort of thing. (excuse my loose wording).
I was thinking of Action Listener interfaces in which callbacks and events are actually used (I assume) to run the methods in our applet classes etc when a button is clicked. But its similar in effect to Thread calling run(). (or have I sinned here?)
blmblm@myrealbox.com - 23 Jul 2005 13:38 GMT >Yes Dale, thats interesting. The thread class behaves > in this way. Once it gets a Runnable object then it [quoted text clipped - 7 lines] >But its similar in effect to Thread calling >run(). (or have I sinned here?) Well, I'm not Dale, but it sounds to me like you're starting to get the hang of interfaces -- the ActionListener interface, like the Runnable interface, allows code in some other class (something in Swing for ActionListener, Thread for Runnable) to make a callback to code in your class (actionPerformed() or run() respectively). Do you also feel like it's starting to make sense to you?
(I'm wondering in writing this reply what you mean by "thats interesting" in your first paragraph. It's obviously a reply to something someone else wrote, but I can't easily find that previous post, and since you didn't quote .... Well, maybe it's just the antique newsreader I use, but I think there's a case to be made for quoting a bit of what you're replying to.)
| B. L. Massingill | ObDisclaimer: I don't speak for my employers; they return the favor. Will - 27 Jul 2005 00:30 GMT > Well, I'm not Dale, but it sounds to me like you're > starting to get the hang of interfaces -- the [quoted text clipped - 12 lines] > newsreader I use, but I think there's a case to be made > for quoting a bit of what you're replying to.) I agree about quoting what your replying to. So many programmers use of language is terrible. They know exactly the flow of their meaning but do their readers? Not often I suggest (or is it just me?) As for Interfaces, all the text books seem to say is 'contracts' and empty methods stubs, but the practical use of Intefaces is usually the fact that the method that is called in our own classes are in fact called from, a helpful class, like Thread or ActionListener where all the hard work is done for us. This is the Multiple Inheritance-like behavior that I was looking for and was never explained in books (or anywhere). Explanations like 'a cat is a mammal that cannot fly and eats fish pizzas but not worms on Sundays' leaves my head reeling. But the looking in the class Thread and actually seeing it call run() after doing a bit of magic is an understandable use of Interfaces IMHO. I think I get them now. THANKS TO ALL (shouting).
or ActionListener
Mike Schilling - 06 Jul 2005 00:09 GMT > Someone please help me out, I've looked at 50+ books on Interfaces. > I understand contracts etc. But how on earth does an Interface method [quoted text clipped - 18 lines] > Will some kind person explain whats going on in simple English that > even I could understand. This is very similar to asking "What does compareTo() have to do with sorting lists?" The answer is that the sort algorithm can be written generically by factoring out how to compare different sorts of objects. If you mandate that an object implement the compareTo method, by insisting that it implement Comparable, than you can write a sort algorithm that contains the fragment:
// compare the two objects if (a.compareTo(b) < 0) { // switch them }
Likewise, the low-level Java code that starts a new thread looks (very loosely) like:
void startThread(Runnable r) { // do magic to create a new stack // do magic to switch to the new stack r.run() }
That is, after creating the new thread in some JVM-specific manner, it calls Runnable.run() to run in that thread, and run() is used as a callback, just as compareTo() is above. Since implementing an interface means implementing methods with given signatures, one of their main uses is to specify that a given callback is available.
billreyn@gmail.com - 06 Jul 2005 09:26 GMT 'run() is used as a callback' this is the magic explanation that I have never understood or even seen in my 50 books.This is beginning to sound rational at long long long last. Why don't books mention 'callbacks' in Interfaces? It simply does not make sense without that (in my small mind). They only ever discuss 'contracts' which I understand completely. I am not exactly sure of the callback process, but will start investigating them (delegates etc) and hopefully will understand completely then. Its got something to do with what calls what and what is 'passed' to what. I shall also look at compareTo()
Chris Uppal - 06 Jul 2005 12:52 GMT > 'run() is used as a callback' this is the magic explanation that I have > never understood or even seen in my 50 books.This is beginning to sound > rational at long long long last. Why don't books mention 'callbacks' in > Interfaces? It simply does not make sense without that (in my small > mind). They only ever discuss 'contracts' which I understand > completely. Probably because interfaces and callbacks are completely separate beasts.
However there /is/ a connection of sorts. If you have some object, and you want to invoke one of its methods, then you have to know that that method exists. A callback is just a special case of invoking a method (there's no formal difference, it's just that some methods are used as callbacks, some are not). So, for the Java runtime machinery to issue the callback method run(), it has to be sure that he method exists. That's where interfaces come in. The interface is (among other things) a contract defining what methods the caller can expect to find. The specific interface java.lang.Runnable, represents the contract that any object that implements that interface will have a void run() method. So, when you start a thread you (normally) provide an object that implements java.lang.Runnable (which is checked by the compiler, and by the runtime), so the system knows that it can safely invoke that object's run() callback method as the body of the new thread.
-- chris
George Cherry - 06 Jul 2005 18:42 GMT >> 'run() is used as a callback' this is the magic explanation that I have >> never understood or even seen in my 50 books.This is beginning to sound [quoted text clipped - 28 lines] > run() > callback method as the body of the new thread. Yes. Maybe this will also help the op: A Thread is a worker; the run() method in an instance of type Runnable defines the work or task that the worker Thread performs. The run() method gives the job (task) description for the worker Thread. Also, the Runnable interface is a more flexible and versatile way to define the work than subclassing Thread in a class that defines run()--since Java has only single inheritance for implementations.
George W. Cherry
Roedy Green - 06 Jul 2005 01:01 GMT >Someone please help me out, I've looked at 50+ books on Interfaces. >I understand contracts etc. But how on earth does an Interface method >do something like start a thread running? eg: see http://mindprod.com/jgloss/interface.html and follow the links.
An interface Object does not exist. However an interface reference to a real object that implements the interface can do any of its methods the interface exposes, but not the rest.
 Signature Bush crime family lost/embezzled $3 trillion from Pentagon. Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video. http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm
Canadian Mind Products, Roedy Green. See http://mindprod.com/iraq.html photos of Bush's war crimes
Thomas Weidenfeller - 06 Jul 2005 09:43 GMT > Someone please help me out, I've looked at 50+ books on Interfaces. > I understand contracts etc. But how on earth does an Interface method [quoted text clipped - 4 lines] > public void run() { > for (int x = 1; x < 100; x++) { // runs a new thread No, it doesn't. It CAN run in a thread - if you tell a thread to do so. It doesn't do it by its own.
> } } > > Above is MY implementation of the Interface method run() (its not > exactly right, no matter), and it will run in its own thread. Only when you tell a thread to do this.
> But I > have not written anything to do with running a thread, so how does it > 'know' to do this special task? (running a thread)??? It doesn't. You have to tell a thread to run it.
> All I do is my > OWN implementation of run() which is just a 'for' loop. How does it > 'know' to run it in its own thread?? It doesn't. Didn't I say this before? :-)
> According to every book I have > read, an Interface only forces me to write my own method with the > method name & params that is in the Interface. hat I understand, so how > does it run a thread? It doesn't. Didn't I ... :-))
> Its not in my implementation. > > Will some kind person explain whats going on in simple English that > even I could understand. A runnable represents a piece of code which can be run by someone. Whoever wants to run that piece of code can run it by calling the run() method.
You can run it yourself by calling the run() method.
If you tell no one to run it, it will not run.
If you tell a thread to run it (in parallel to your current thread), the thread will run it by calling the run() method of the runnable:
Runnable codeToRun = new TryThreads(); Thread aThread = new Thread(codeToRun); aThread.start(); // runs the code in a separate thread
"new Thread(codeToRun)" creates a new thread object, which is not running at this point. But which already knows that the thread, when started, should run the code in "codeToRun". The call to start() indeed starts the thread, which will do what it has been told: run the "codeToRun", by calling codeToRun.run().
/Thomas
 Signature The comp.lang.java.gui FAQ: ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
billreyn@gmail.com - 06 Jul 2005 18:17 GMT Thanks Thomas, its slowly starting to make sense. Its at the limits of my intelligence though.
"." - 06 Jul 2005 16:37 GMT > Someone please help me out, I've looked at 50+ books on Interfaces. > I understand contracts etc. But how on earth does an Interface method > do something like start a thread running? eg: You are mixing two things here. An interface is just a way of listing the methods you want someone to create. For example, if your class implements the Runnable interface you are required to have a public method called run that takes no inputs and returns void. If you implement this interface you have not created a thread. The creating of a Thread is something COMPLETELY seperate.
> class TryThreads implements Runnable > { > public void run() { > for (int x = 1; x < 100; x++) { // runs a new thread > } } The above class implements the interface Runnable. This does not make it a Thread. I might create a project that requires a type called NotAThread. My code is going to assume that the class NotAThread will have a method called run that takes no inputs and returns void. Rather than create an interface to enforce this requirement I see that there is an interface called Runnable so I just use that. My project has nothing to do with Thread but I can still use the Runnable interface.
> Above is MY implementation of the Interface method run() (its not > exactly right, no matter), and it will run in its own thread. Incorrect. Your above call has little to do with threads. On its own it cannot run as a thread. All the magic to do that is in the Thread class. The interface Runnable determines WHAT will become a thread. It does not determine HOW something will become a thread.
> But I have not written anything to do with running a thread, so how does > it 'know' to do this special task? (running a thread)??? All I do is my [quoted text clipped - 6 lines] > Will some kind person explain whats going on in simple English that > even I could understand. What you really want to understand is not interfaces but Thread.
You can create a thread by passing Thread a class that implements Runnable.
The interface Runnable is just a contract between Thread and your class promising that you have created a method called run that requires no inputs and returns void. What Thread does with that method is the magic that is threads.
The interface Runnable tells us WHAT method is going to be turned into a thread. It does not tell us HOW it is turned into a thread.
Interfaces tell us WHAT methods are needed. It is a completely seperate issue as to WHY those methods are needed and HOW they will be used.
 Signature Send e-mail to: darrell dot grainger at utoronto dot ca
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|