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 don't 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:


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:


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();
    }
}

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: