How to create a thread

Execution in Java always take form of a thread. In simple programs only one thread occurs, often referred to as the "main thread".In some programs though concurrent threads is necessary, or if you are building a Swing application with for example a progress bar you dont want the main thread to handle the updates of the UI.
Then you create an additional thread to take care of that. There are two main ways of creating a thread. The first is to extend the Thread class and the second is to implement the Runnable interface.

Extending Thread: This examplse shows how you can create a thread in java by extending the thread interface.

public class MyThread extends Thread {
    
    /**
     * This method is executed when the start() method is called on the thread
     * so here you will put the "thread code"
     */

    public void run() {
        System.out.println("Thread executed!");
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        Thread thread = new MyThread();
        thread.start();
    }
}

Implementing the Runnable interface:  The below example shows how to create a thread in java by implementing the runnable interface

public class MyRunnable implements Runnable {
    
    /**
     * As in the previous example this method is executed
     * when the start() method is called on the thread
     * so here you will put the "thread code".
     */

    public void run() {
        System.out.println("Thread executed!");
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {

   //create a Thread object and pass it an object of type Runnable
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)