Start a thread in Java

problem

You wish to create a multithreated Java application and you want to know how to start with concurrent programming. In this post we will see the two classic ways of starting an additional thread from your program.

solution

Java has a Thread class that we can simply extend and add our piece of code that will run in its own Thread. It can start executing it on demand. For example:

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("MyThread is running...");
    }
    
}

Simply extend the Thread class and override its run method.

In order for this thread to run we first need to initialize it and afterwards to start it. For example:

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

In the main method we instantiate a MyThread object and then we invoke start() and it starts running. In fact, first it’s being scheduled and then it is run. The start method will invoke the run method at some point; we never invoke run method direcctly as it will not be treated as thread code but instead as normal method invocation.

Putting it all together:

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("MyThread is running...");
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
Running output
MyThread is running...

Option 2

The other option to start a Thread is by creating a class that is implementing the Runnable interface. For example:

public class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println("MyThread is running...");
    }
}

Similar to the previous approach, we still override the run method and place the code that we want to be executed. Now if we want to start it, we will need to instantiate a Thread object and pass an instance of MyThread as a parameter in the constructor. For example:

MyThread myThread = new MyThread();
Thread t1 = new Thread(myThread);
t1.start();

The only difference here is that we need an instance of Thread so we can invoke its start method.

Putting it all together, will be like:

public class MyThread implements Runnable {

    @Override
    public void run() {
        System.out.println("MyThread is running...");
    }

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

When we invoke the start method on t1, behind the scenes it’s also scheduled and then it’s using the implemented Runnable (myThread) and invoking its run() method.

Running output
MyThread is running...

Slightly different approach on the invocation part but with big differences if we compare them. One of the positives the second approach has it is that you can still extend a class but with the other option since you’re extending the Thread class, no more classes can be extended as it impossible to extend multiple classes in Java.

Conclusion

We simply saw the two ways of starting a new thread in Java. One can use this as a starter point to build multi-threaded applications.


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.