Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: relationship of the Runnable and Thread interfaces

Tags:

java

interface

I realize that the method run() must be declared because its declared in the Runnable interface. But my question comes when this class runs how is the Thread object allowed if there is no import call to a particular package? how does runnable know anything about Thread or its methods? does the Runnable interface extend the Thread class? Obviously I don't understand interfaces very well. thanks in advance.

    class PrimeFinder implements Runnable{
         public long target;
         public long prime;
         public boolean finished = false;
         public Thread runner;
         PrimeFinder(long inTarget){
              target = inTarget;
              if(runner == null){
              runner = new Thread(this);
              runner.start()
         }
    }
    public void run(){

    }
}
like image 266
Karl Patrick Avatar asked Dec 28 '22 23:12

Karl Patrick


2 Answers

In this situation, I like to think of interfaces as contracts. By saying that your class implements Runnable, you are explicitly stating that your class adheres to the Runnable contract. This means that other code can create an instance of your class and assign to a Runnable type:

Runnable r = new PrimeFinder();

Further, by adhering to this contract you are guaranteeing that other code calling your class can expect to find the methods of Runnable implemented (in this case run() ).

like image 55
D.C. Avatar answered Dec 31 '22 13:12

D.C.


Nope. Thread is in lava.lang package, so it's implicity imported.

And: Thread knows Runnable.

That's why Thread receives an Runnable (this implements Runnable) and calls its method run() inside its own thread of execution.

The Thread mantains a reference to the Runnable you implement:

public Thread(Runnable runnable) {
   this.myRunnable = runnable;
}

private Runnable myRunnable;

The start method of Thread class could look like:

public void start() {
  // do weird stuff to create my own execution and...
  myRunnable.run();
}
like image 35
helios Avatar answered Dec 31 '22 14:12

helios