Wednesday, April 7, 2010

Java Thread:: Part 2

For creating any thread class has to do following 2 steps:
  1. Have direct/indirect instance of class Thread.
  2. In order to satisfy 1, you need to have directly or indirectly implement Runnable interface.
With these 2 conditions implemented, you can create thread in Java.
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:

  1. 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.
  2. 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.
These are 2 ways to implement the Threads in java.
Next Article:: Synchronization in java

No comments:

Post a Comment