Multithreaded programming with Java.

A thread is the smallest sequence of instruction executions which can be scheduled by an OS scheduler to run on a CPU. A thread is living inside a process and it is considered as a lightweight process.

Threads are the fundamental model of program execution in a Java program, and the Java language and its API provide a rich set of features for the creation and management of threads. All Java programs comprise at least a single thread of control—even a simple Java program consisting of only a main() method runs as a single thread in the JVM. Java threads are available on any system that provides a JVM including Windows, Linux, and Mac OS. The Java thread API is available for Android applications as well.

In Java there are two ways to create thread objects

  1. By implementing the Runnable interface.
  2. By extending the Thread class.

Runnable interface implementing technique is the most widely used technique by the programmers to create explicit threads in java programs.

This interface defines a single abstract method with the signature public void run(). The code in the run() method of a class that implements Runnable is what executes in a separate thread.

Here are some important discussions between these two thread creating techniques in java.

  • When we extend Thread class, we can’t extend any other class even we require and When we implement Runnable, we can save a space for our class to extend any other class in future or now.
  • When we extend Thread class, each of our thread creates a unique object and associate with it. When we implements Runnable, it shares the same object to multiple threads

Let’s start multi-threaded programming through the Runnable interface.

Here we can create two classes, one class for implementing the Runnable interface and the other class for executing the thread through the run() method that is declared in the Runnable interface(overridden by the implemented class).

public class RunnableMethod implements Runnable {

    @Override
    public void run() {
        System.out.println("Hello Thread");
    }
}

The Runnable interface contains only one method called run(), which must be Overided when you implement it. The task that we expect to be done as a thread is defined in the run() method, and here it is just a System.out.println() statement which prints “Hello Thread”.

and we need another class for executing the Thread, since we just have only defined the task in the run() method.

public class ThreadExecutor {
    public static void main(String[] args) {
        RunnableMethod runnableMethod = new RunnableMethod();

        Thread thread = new Thread(runnableMethod);

        thread.start();
    }
}

Here we have created an object of the RunnableMethod class, and then it is passed as an argument of the Thread instance. In order to start our work as an independent thread, we have to start it by invoking the start() method that you can see in the above block of codes.

Now we have defined our first java explicit threaded application which contains only one explicit java thread. In order to do that we have defined two java classes which are RunnableMethod and ThreadExecutor. But with the development of Java, we can use lambda expressions to do the above work only using one single class as follows.

public class JavaThreadLambda {
    public static void main(String[] args) {

        Runnable runnableMethod = () -> System.out.println("Hello Thread");

        Thread thread = new Thread(runnableMethod);
        thread.start();
    }
}

Note| we can do this because the Runnable interface contains only one single abstract method.

Until now, we just created a single-threaded program. But we can create more threads like the following program which contains two.

public class JavaThreadLambda {
    public static void main(String[] args) {

        Runnable runnableMethod = () -> {
            while(true) {
                System.out.println(Thread.currentThread().getName());
            }
        };

        Thread threadOne = new Thread(runnableMethod);
        Thread threadTwo = new Thread(runnableMethod);

        threadOne.start();
        threadTwo.start();
    }
}

In the above program, I have used an infinity while loop to clearly show you how the threadOne and threadTwo are working concurrently. In addition to that I have used some new methods inside the System.out.println() statement, that shows you the currently executing thread number.

It is better if you can run this program on your IDE and learn your own what is happening in the program

Let’s start multi-threaded programming by extending the Thread class.

Creating threads by extending the Thread class is a bit easier than implementing the Runnable interface. However, as we know Java does not allow us to do multiple inheritances. So, once we extend the Thread class then there is no chance to extend another class, but you can implement interfaces. That is the main problem when you extend the Thread class to do multi threading in your program.

But there are some times you do not need to extend other classes. So this method will be good for those times.

The following program shows you the structure of a simple multi-threaded program that is programmed by extending the Thread class.

public class ThreadExtender extends Thread {
    @Override
    public void run(){
        while(true) {
            System.out.println(currentThread().getName());
        }
    }

    public static void main(String[] args) {
        ThreadExtender threadOne = new ThreadExtender();
        ThreadExtender threadTwo = new ThreadExtender();

        threadOne.start();
        threadTwo.start();
    }
}

Note| Now, it is clear that we must execute our threads through the run() method. But as you see here we use the start() method instead of run(). So, the reason for that is when you invoke the start() method, it will execute the run() method on a new thread. But if you directly call the run() method then a new thread will not be created, all the threads will be executed on the main thread. You can see this by changing the method threadOne.start() and threadTwo.start() to threadOne.run() and threadTwo.run().

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.