Thread creation in java - Java @ Desk

Monday, June 3, 2013

Thread creation in java

There are two ways to create and run a thread in java:
1) Create a Thread class object
2) Implement a Runnable interface

In both the cases, we need to override a run() method which enters the created thread into running state. Also, the thread enters into runnable state by calling the start() method on the thread object.

The only difference is that the Thread implementation calls the start() method on the class object that extends the Thread class. Whereas, in case of Runnable implementation, start() method gets called on the new Thread(new Class_Object) method, where Class_Object is the class that implements the Runnable interface.

Runnable Implementation:

public class RunnableImplementation implements Runnable {

    public void run() {
        System.out.println("This thread is created using the Runnable implementation");
    }

    public static void main(String args[]) {
        new Thread(new RunnableImplementation()).start();
    }
}
Thread implementation:

public class ThreadCreation extends Thread {

    public void run() {
        System.out.println("This thread is created by extending the Thread class");
    }

    public static void main(String args[]) {
        (new ThreadCreation()).start();
    }
}

Other references on threads
Difference between sleep and wait in java
Lifecycle of thread
Difference between yield and sleep in java
Thread creation in java







No comments:

Post a Comment