Threads in Java- Part 3 (Implementing thread using runnable interface)
In the previous article, we discussed about the creating thread by extending thread class. In this article, we are gonna discuss about the creating a thread by using a runnable interface.
Below show how can I declare a class to call runnable interface. We can use “implements” keyword to implement interface. We know that interfaces do not have any king of implemented methods. As said before, when we implement interface, we must need to override the run(). Because, it is must to override the behaviors declare within the interface.
In that case, our interface is Runnable and it has a run method inside that.
In order to create a thread and execute this program we wanna do some small modifications in our main method. As you can see we do not have start() inside of Runnable to create a new thread. Therefore, we should instantiate an object from a thread class in main method and pass runnable instance for that as below. Then we can create a new thread by calling thread.start().
This is how we can create a thread by implementing runnable interface with Java.
Hope you get clear understand about how we can implement interface to create thread. In my next article, we are going to discuss about the different constructors in Thread class.
Stay Safe !!!
References:
https://www.youtube.com/watch?v=jeGuZeahWWQ&list=PLD-mYtebG3X99o6vJ3uR5P6UcH3MQSWBH&index=3
