Java Threads - Two ways of Thread Creation


A Thread, we said, is a separate execution paths within a process.

Threads in Java can be created in two ways:

  1. By extending the java.lang,Thread class.
  2. By implementing the Runnable interface.

1. Extending Thread

A thread can be created by deriving from the Thread class.

public class CreateThread  extends Thread{..}

Thread class is defined in the java.lang package.

We then override it's run method.

@Override
    public void run() {
        //do something here

    }

This run() method is the entry point to the thread.

We supply the code that we want executed in the thread inside it. That code will then run concurrently with other threads.

Even though our class has extended the Thread class and implemented the run(), the thread does not just start automatically.

We have to start it explicitly for that we need an object of our class that has inherited from Thread class.

So we instantiate it:

CreateThread myThread=new CreateThread();

To start the the thread, we have to use the start() method:

myThread.start();

Here's the full code:


package createthread;

public class CreateThread  extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }
    }
    public static void main(String[] args) {
        CreateThread myThread=new CreateThread();
        myThread.start();
    }
}

Result

0
1
2
3
4
5
6
7
8
9

How the start() method works

The start(), we said starts the thread explicitly.

When we run our project and the JVM(Java Virtual Machine) encounters the start() method, it spawns a new control of execution. Then it returns to the main thread.

The two threads: the spawned thread and the main thread run concurrently.

The main thread will execute statements we we write before and after the start() method.

The spawned thread will execute statements we write inside the run() method.

Let's look at an example:


package createthread;

public class CreateThread  extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i+" inside Spawned Thread");
        }
    }
    public static void main(String[] args) {
        CreateThread myThread=new CreateThread();
        myThread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println(i+ "---- INSIDE THE MAIN THREAD----");
        }
    }
}

Result

0 inside Spawned Thread
0---- INSIDE THE MAIN THREAD----
1 inside Spawned Thread
2 inside Spawned Thread
3 inside Spawned Thread
4 inside Spawned Thread
5 inside Spawned Thread
1---- INSIDE THE MAIN THREAD----
6 inside Spawned Thread
2---- INSIDE THE MAIN THREAD----
7 inside Spawned Thread
8 inside Spawned Thread
3---- INSIDE THE MAIN THREAD----
9 inside Spawned Thread
4---- INSIDE THE MAIN THREAD----
5---- INSIDE THE MAIN THREAD----
6---- INSIDE THE MAIN THREAD----
7---- INSIDE THE MAIN THREAD----
8---- INSIDE THE MAIN THREAD----
9---- INSIDE THE MAIN THREAD----

Clearly you can see that the two threads are running concurrently based on the results we are getting.

There is really no pre-defined order in which the threads will run and running this example over and over again will produce different results. This is because the Operating System has a scheduling policy that results in it running the threads on an interleaved pattern suitable based on the available resouces.

Implementing Runnable

Runnable is an interface that also allows to also create threads.

Remember Java does not support multiple inheritance, hence by us having derived from Thread class in the previous class, we cannot further derive from other classes.

This limits the design of our application. Hence we can alternatively use an interface since Java allows us implement arbitrary number of interfaces.

All we have to do is implement the Runnable interface:

public class MrRunnable implements Runnable {..}

Then override the run() method:

    public void run() {
        //do stuff here
    }

However be aware that the instance of this class isn't a thread. All it's capable of is that it's run() method can be executed concurrently with other threads.

Now to create the Thread object, we have two constructors we can use:

public Thread(Runnable target)
public Thread(Runnable target, String name)

The instance of the Runnable, in our case the instance of MrRunnable class, is supplied as the first argument.

Then we can now instantiate the Thread:

Thread t = new Thread(new MrRunnable());

Then we start the thread as usual using the start() method.

Here's an example:

package mrrunnable;

public class MrRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i+" inside Spawned Thread");
        }
    }
    public static void main(String[] args) {
        Thread myThread=new Thread(new MrRunnable());
        myThread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println(i+ "---- INSIDE THE MAIN THREAD----");
        }
    }
}

Result:

0---- INSIDE THE MAIN THREAD----
0 inside Spawned Thread
1 inside Spawned Thread
1---- INSIDE THE MAIN THREAD----
2 inside Spawned Thread
3 inside Spawned Thread
4 inside Spawned Thread
5 inside Spawned Thread
6 inside Spawned Thread
2---- INSIDE THE MAIN THREAD----
7 inside Spawned Thread
3---- INSIDE THE MAIN THREAD----
8 inside Spawned Thread
4---- INSIDE THE MAIN THREAD----
9 inside Spawned Thread
5---- INSIDE THE MAIN THREAD----
6---- INSIDE THE MAIN THREAD----
7---- INSIDE THE MAIN THREAD----
8---- INSIDE THE MAIN THREAD----
9---- INSIDE THE MAIN THREAD----

Try running the program repeatedly and you'll see the results changing. We said earlier that this is because the threads are scheduled by the Operating System which has it's own independent policy based on the available resources at each moment.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post