How do I start a thread execution?

To make a thread begin its execution, call the start() method on a Thread or Runnable instance. Then the Java Virtual Machine will calls the run method of this thread.

The snippet below is showing how to create a thread by implementing the Runnable interface.

package org.kodejava.example.lang;

public class ThreadRun implements Runnable {

    public void run() {
        System.out.println("Running..");
    }

    public static void main(String[] args) {
        //
        // Instantiate ThreadRun
        //
        ThreadRun tr = new ThreadRun();

        //
        // Create instance of Thread and passing ThreadRun object
        // as argument.
        //
        Thread thread = new Thread(tr);

        //
        // By passing Runnable object, it tells the
        // thread to use run() of Runnable object.
        //
        thread.start();
    }
}

The snippet below is showing how to create a thread by extending the Thread class.

package org.kodejava.example.lang;

public class ThreadStart extends Thread {
    //
    // The run() method will be invoked when the thread is started.
    //
    @Override
    public void run() {
        System.out.println("Running..");
    }

    public static void main(String[] args) {
        ThreadStart thread = new ThreadStart();

        //
        // Start this thread
        //
        thread.start();
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply