Skip to content

Creating a thread in java

Implementing the Runnable Interface

The simplest way is to create a class that implements the Runnable interface. Runnable represents a chunk of code that can be executed. You can build a thread using any object that implements Runnable. To implement Runnable, a class only needs to have a single method called run(), which looks like this: public void run()

Inside the run() method, you define the code that will run in the new thread. It’s essential to understand that run() can do anything the main thread can do: call other methods, use other classes, and declare variables. The only difference is that run() sets up the starting point for another, separate thread of execution within your program. This thread will finish when run() finishes.

Once you’ve created a class that implements Runnable, you make an object of type Thread from within that class. Thread has various constructors, but the one we’ll use looks like this: Thread(Runnable threadOb, String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable interface, which indicates where the thread’s execution will begin. You can also specify the name of the new thread using threadName.

After the new thread is made, it won’t start running until you call its start() method, which is declared within Thread. Essentially, start() triggers a call to run(). The start() method looks like this: void start():

java
public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running!");
    }
}

public class ThreadCreationExample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

Here, we define a class MyRunnable that implements the Runnable interface. It has a run() method where we put our task logic. Then, in our ThreadCreationExample, we create a Thread object, passing our MyRunnable instance to it, and start the thread.

Extending the Thread Class

Another way to create a thread is by making a new class that extends the Thread class and then creating an object of that class. This new class must replace the run() method, which acts as the starting point for the new thread. It also has to invoke the start() method to kick off the execution of the new thread. Below is the previous program modified to use the Thread extension method:

java
public class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running!");
    }
}

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

In this example, we create a class MyThread that extends the Thread class. We override the run() method with our task logic. Then, in our ThreadCreationExample, we create an instance of MyThread and start it.

Personal Reflection

Creating threads in Java opens up a world of possibilities. It's like having a team of workers at your disposal, each handling different tasks simultaneously. Whether you choose to implement the Runnable interface or extend the Thread class, the goal remains the same—to make your Java programs more efficient and responsive.

Multipe Threads

your program can make as many threads as necessary. For instance, the code below shows how to create three new threads:

java
class MyThread implements Runnable {
Thread thrd;

    // Construct a new thread.
    MyThread(String name) {
        thrd = new Thread(this, name);
        thrd.start(); // start the thread
    }

    // Begin execution of new thread.
    public void run() {
        System.out.println(thrd.getName() + " starting.");
        try {
            for (int count = 0; count < 10; count++) {
                Thread.sleep(400);
                System.out.println("In " + thrd.getName() + ", count is " + count);
            }
        } catch (InterruptedException exc) {
            System.out.println(thrd.getName() + " interrupted.");
        }
        System.out.println(thrd.getName() + " terminating.");
    }
}

class MoreThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");

        MyThread mt1 = new MyThread("Child #1");
        MyThread mt2 = new MyThread("Child #2");
        MyThread mt3 = new MyThread("Child #3");

        for(int i=0; i < 50; i++) {
            System.out.print(".");
            try {
                Thread.sleep(100);
            } catch (InterruptedException exc) {
                System.out.println("Main thread interrupted.");
            }
        }
        System.out.println("Main thread ending.");
    }
}

In this example, MyThread implements the Runnable interface. It starts a new thread in its constructor and defines the run() method to execute the thread’s tasks. The MoreThreads class creates three instances of MyThread, each running concurrently with the main thread.

Main thread starting.
.Child #1 starting.
Child #3 starting.
Child #2 starting.
...In Child #1, count is 0
In Child #3, count is 0
In Child #2, count is 0
....In Child #3, count is 1
In Child #1, count is 1
In Child #2, count is 1
....In Child #3, count is 2
In Child #1, count is 2
In Child #2, count is 2
...In Child #3, count is 3
.In Child #1, count is 3
In Child #2, count is 3
...In Child #3, count is 4
In Child #1, count is 4
In Child #2, count is 4
....In Child #3, count is 5
In Child #2, count is 5
In Child #1, count is 5
....In Child #3, count is 6
In Child #2, count is 6
In Child #1, count is 6
...In Child #3, count is 7
In Child #2, count is 7
.In Child #1, count is 7
...In Child #3, count is 8
In Child #2, count is 8
In Child #1, count is 8
....In Child #3, count is 9
Child #3 terminating.
In Child #2, count is 9
Child #2 terminating.
In Child #1, count is 9
Child #1 terminating.
............Main thread ending.

Example 2

java
public class MyThread extends Thread {
    public void run() {
        System.out.println("Hello from a new thread!");
    }
}

public class MultiThreadExample {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();

        thread1.start();
        thread2.start();

        System.out.println("Main thread exiting.");
    }
}

In our example, we've created a class called MyThread, which extends the Thread class—a built-in class in Java for creating threads. Inside MyThread, we override the run() method, where we specify the code that the thread will execute when it's started.

Next, in our MultiThreadExample, we create two instances of MyThread, thread1, and thread2. We then start both threads using the start() method, which kicks off their execution asynchronously. Finally, we print a message from the main thread, indicating that it's exiting.

Now, let's break down what's happening:

  • When we start thread1 and thread2, they each begin executing their run() method concurrently with the main thread.
  • As a result, we'll see the "Hello from a new thread!" message printed multiple times, potentially interleaved with the main thread's message.

Isn't that fascinating? By creating multiple threads, we can harness the power of concurrency to accomplish more in less time.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.