Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > What is an interface?

Reply
Thread Tools

What is an interface?

 
 
billreyn@gmail.com
Guest
Posts: n/a
 
      07-05-2005
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.

 
Reply With Quote
 
 
 
 
Chris Smith
Guest
Posts: n/a
 
      07-05-2005
<(E-Mail Removed)> wrote:
> 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)???


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.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
Reply With Quote
 
 
 
 
billreyn@gmail.com
Guest
Posts: n/a
 
      07-05-2005
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!

 
Reply With Quote
 
Daniel Dyer
Guest
Posts: n/a
 
      07-05-2005
On Tue, 05 Jul 2005 21:50:01 +0100, <(E-Mail Removed)> wrote:

> 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!


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.


--
Daniel Dyer
http://www.dandyer.co.uk
 
Reply With Quote
 
billreyn@gmail.com
Guest
Posts: n/a
 
      07-05-2005
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.

 
Reply With Quote
 
Mike Schilling
Guest
Posts: n/a
 
      07-05-2005

<(E-Mail Removed)> wrote in message
news:(E-Mail Removed) oups.com...
> 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.


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.


 
Reply With Quote
 
Mike Schilling
Guest
Posts: n/a
 
      07-05-2005

<(E-Mail Removed)> wrote in message
news:(E-Mail Removed) oups.com...
>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)?


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.


 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      07-06-2005
On 5 Jul 2005 13:26:11 -0700, http://www.velocityreviews.com/forums/(E-Mail Removed) wrote or quoted :

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

--
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/...s_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
Reply With Quote
 
Chris Head
Guest
Posts: n/a
 
      07-06-2005
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

(E-Mail Removed) wrote:
> 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)?

[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
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)

iD8DBQFCy3TxgxSrXuMbw1YRAgGrAKCBEhLrG1Xim0dC42kFq8 74Pae31QCfawfK
QDN3+6bp9IdjE2elToguKBY=
=zTIQ
-----END PGP SIGNATURE-----
 
Reply With Quote
 
billreyn@gmail.com
Guest
Posts: n/a
 
      07-06-2005
'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()

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments