+ 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?

24th Dec 2017, 4:09 PM
ziggy
3 Réponses
+ 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(); } }
24th Dec 2017, 9:18 PM
Vukan
Vukan - avatar
+ 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?
24th Dec 2017, 9:24 PM
ziggy
+ 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);
25th Dec 2017, 12:00 AM
Dan Walker
Dan Walker - avatar