Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interface question

I'm confused (new to java):

When implementing the Runnable interface, one must override the run() method to get thread execution capability. Implementing this interface makes your object a type Runnable (?). How does the thread functionality get "injected" by simply implementing the Runnable interface? Basically when you instantiate a class that implements Runnable, what is going on that ties in the threading functionality? I am probably misunderstanding some basing OO concept here. Thanks.

Is it the JVM that "knows" to look for a runnable when doing a thread.start()?

like image 865
ikp Avatar asked Nov 30 '22 18:11

ikp


1 Answers

When you create an implementation of Runnable, nothing ties your class to the thread capacities of the JVM. An instance of the Runnable interface is like an instance of any other interface, just another instance.

If you want to use the threading system of the JVM, you have to use a new instance of the Thread class, that will run the run() method of your Runnable implementation in a separate thread.

All the logic about creating a new thread is done by the Thread class.

like image 142
Vivien Barousse Avatar answered Dec 04 '22 14:12

Vivien Barousse