+ 2
Creating Thread objects from interface
In the example, they don’t extend the Thread class, but instead implement the Runnable interface. How will this provide access to the Thread class and the ability to instantiate new threads?
3 Respuestas
+ 8
like this:
class Loader implements Runnable {
public void run() {
System.out.println("Hello");
}
}
class MyClass {
public static void main(String[ ] args) {
Thread t = new Thread(new Loader());
t.start();
}
}
+ 1
Yes, I see how they use the Runnable interface, but how can you create a Class (the Thread class) which isnt imported/extended to the current class? Does the interface provide access to the class?
+ 1
I think I get what you are asking..
So in this case we aren't making a thread object (we are not extending the Thread class) but we are making a Runnable object which we pass to the constructor of a Thread.
Vukan's code shows that we pass Loader to a Thread, more explicitly
Runnable myLoader = new Loader();
Thread myThread = new Thread(myLoader);