An Introduction to Java Threads

Threads in Java are a convenient way to run multiple tasks concurrently (i.e. simultaneously), to optimise for performance and ressource usage (CPU for example).

Next to the main thread, you can implement worker threads. This can be done through two ways, the first being preferred to the second.

Implementing the Runnable interface

By implementing the Runnable interface and overriding the run-method, a first worker thread can be created:

public class Hello implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

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

}

Extending the Thread class

The Thread class implements itself the Runnable interface but once extended( as in the example below) it cannot be used for further inheritance. It is therefore advisable to rather use the earlier mentioned way of implementing the Runnable interface. You will also need to override the run-method in this case:

public class Hello extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

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

}

Some useful methods for managing threads in Java

run() (return type void)- basically starts the processing of the thread that was invoked by passing a Runnable object. Can be invoked multiple times.

start() (return type void)- creates a totally new thread and then executes the run() method on the newly created thread. Can be invoked only once.

static sleep() (return type void) - sleeps a thread for a specified amount of time.

static currentThread() (return type Thread) - returns the reference to the currently executing Thread.

getName() (return type String) - returns the name of the thread.

stop() (return type void) - stops the thread.