Showing posts with label Java Thread. Show all posts
Showing posts with label Java Thread. Show all posts

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

Monday, April 5, 2010

Different Thread State

There can be following states:

  1. NEW ---> A thread that has not yet started is in this state. In this state, no system resources have been allocated as yet.
  2. RUNNABLE ---> Once start method is invoked thread enter in this state.
  3. BLOCKED ---> A thread that is blocked waiting for a monitor lock is in this state.
  4. WAITING ---> A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  5. TIME_WAITING ---> A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
  6. TERMINATED ---> A thread that has exited is in this state.
These states are related to JVM not operating system thread states.

Sunday, April 4, 2010

Java Thread:: Quick Reference

Today's topic is threads in Java. So, following things I am going to add here.
  1. Different Thread states
  2. How threads can be implemented in JAVA
  3. Different Classes that we may need
  4. Context Switching
  5. Reason why some methods has been deprecated
  6. A bit on synchronisation.