- Have direct/indirect instance of class Thread.
- In order to satisfy 1, you need to have directly or indirectly implement Runnable interface.
So, for doing these 2 things, there are 2 ways in java.
Way 1:
Class can implement Runnable interface and an instance of this class is passed to Thread class.
Way 2:
Class can extend Thread class. And then instance of super or itself will be helpful in creating any thread.
Now, we have question why these rules apply to implement java threads. Then here is the logic:
- As we know that "start" is the method which is called to start the thread. And this method has following signature:
public synchronized native void start();
As this method is native, which directly means that creation of thread, allocation of system resource goes here. And in Java thread is the only class which does that. So, this give to origination to the rule 1 i.e. have instance of Thread class. - Related to second rule, i.e. implement Runnable class. Reason is that the constructor of Thread class can accept any instance of class which would implement Runnable interface. So, class has to implement the this interface.
Next Article:: Synchronization in java