Multithreading Java Example –

Multithreading Java Example – Example 1

Introduction

To understand multithreading is good to start with the simplest example, a program that uses just one thread and then we will work our way to more complex examples that run multiple threads. In this article we have 4 examples starting from the simplest example and moving forward to a more complex example.

In this particular multithreading java example program, we will see the use of the currentThread() method as a way to control the main thread. We will discuss the setName() method, the sleep() method and the use of try/catch logic to handle the Interrupted Exception.

CurrentThreadSample program:

package current.thread.method;

class CurrentThreadSample {

    public static void main(String[] args) {

        Thread t1 = Thread.currentThread();

        System.out.println(“The current thread running is:” + t1);

        t1.setName(“NewRenamedThread”);

        System.out.println(“The new renamed thread is “ + t1);

        try {

            for (int i = 0; i < 10; i++) {

                System.out.println(i);

                Thread.sleep(1000);

            }

        } catch (InterruptedException e) {

            System.out.println(“Interrupted the main thread”);

        }

    }

}

 

Using the current thread method

 

Thread t1 = Thread.currentThread();
The instruction above in the program CurrentThreadSample calls the currentThread() method and this method returns a reference to the main thread which is, by the way, the “current thread” running at the moment. This reference is stored in a variable called t1.

System.out.println(“The current thread running is:” + t1);

In this instruction, we just display information about the thread in this case the program when run displayed the following line:

The current thread running is: Thread[main, 5, main]

Using the setName() method

t1.setName(“NewRenamedThread”);

In the instruction above the program changes the internal name of the thread by using the Thread method setName().

System.out.println(“The new renamed thread is ” + t1);

This line of code redisplays information about the thread, but in this case the internal name of the thread was changed with the setName() method and this change is reflected. When we ran the program this was displayed:

The new renamed thread is Thread[NewRenamedThread, 5, main]

The sleep method and how to handle exceptions

        try {

            for (int i = 0; i < 10; i++) {

                System.out.println(i);

                Thread.sleep(1000);

            }

        } catch (InterruptedException e) {

            System.out.println(“Interrupted the main thread”);

        }

The block of code above is a loop that counts from 0 to 9, and prints the iteration number to the console, also it pauses one thousand milliseconds (one second) in between each printed line.

The program uses the sleep method of the Thread class:
“Thread.sleep(1000);”

The argument in between parenthesis is the delay period in milliseconds.  There is the possibility that the sleep() method of the Thread class throws an Interrupted exception, and that is why we surround the sleep() method statement with a try/catch block.

An Interrupted exception might be thrown if some other thread tried to interrupt this one while it is in the sleep() State. In this particular program, we handle the InterruptedException by just printing a message, but in a production environment, we would handle the exception differently.

Result of running the program

Here is a sample of the output produced by the program when is run:

The current thread running is: Thread[main, 5, main]
The new renamed thread is Thread[NewRenamedThread, 5, main]
0
1
2
3
4
5
6
7
8
9
System.out.println(“The new renamed thread is ” + t1);

In the instruction above notice that t1 is used in the println method.  The result is to display a line like below:

The new renamed thread is Thread[NewRenamedThread, 5, main]

As we can see there are 3 pieces of information displayed: the name of the thread (NewRenamedThread), the priority of the thread (5), and the name of the thread group (main). When the program started and by default, the name of the “main thread” is “main”, and its priority is 5 and the thread group is also called “main”.  We changed the name of the thread in the following instruction:

t1.setName(“NewRenamedThread”);

After the above instruction was executed the name of the thread is no longer “main”, now is “NewRenamedThread”. A thread group is a data structure. The purpose of the thread group is to control the state of a collection of threads as a whole.

Other methods of the Thread class

Now let’s talk about methods used inside the program, specifically methods that belong to the Thread class. The sleep() method suspends the execution of the running thread for a specific amount of milliseconds. The signature of the sleep method usually is as follows:

sleep(long milliseconds) throws InterruptedException

The sleep() method throws an InterruptedException and its argument is a number of milliseconds. The sleep() methods also have another signature:

static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

This second signature can be used in environments that allow nanoseconds as timing periods.

Another method used by this sample program is setName(). The setName() also has a counter part method called getName(). We did not use getName() in the program but is worth mentioning it. The signatures for this methods are as follows:

final void setName(String threadName)
final String getName( )

Multithreading Java Example – Example 2

Let’s look at another program, actually is 2 programs or classes. The first class is called the RunnableClass and the second class is called MainClass.

package implementing.runnable;

class RunnableClass implements Runnable {

    Thread t2;

    RunnableClass() {

        t2 = new Thread(this, “Created Thread”);

        System.out.println(“A Child thread was just instantiated”);

        System.out.println(“The Child thread name is “ + “[“ + t2.getName()

                + “]” + ” its priority is: “ + “[“ + t2.getPriority() + “]”

                + ” and its group is “ + “[“ + t2.getThreadGroup().getName()

                + “]”);

    }

    public void run() {

        try {

            for (int i = 0; i < 7; i++) {

                System.out.println(t2.getName() + ” “ + i);

                Thread.sleep(300);

            }

        } catch (InterruptedException e) {

            System.out.println(e.getMessage());

        }

        System.out.println(“Exiting “ + t2.getName());

    }

}

public class MainClass {

    public static void main(String[] args) {

        Thread t1 = Thread.currentThread();

        t1.setName(“MainThreadRenamed”);

        RunnableClass rc = new RunnableClass();

        rc.t2.start();

        try {

            for (int i = 0; i < 3; i++) {

                System.out.println(t1.getName() + ” “ + i);

                Thread.sleep(1000);

            }

        } catch (InterruptedException e) {

            System.out.println(e.getMessage());

        }

        System.out.println(t1.getName() + ” thread finishing run.”);

    }

}

In the RunnableClass we have a constructor. In the constructor we create a new Thread object, see the statement below:

t2 = new Thread(this, “Created Thread”);

We pass “this” as the first argument in the statement above. Passing “this” as an argument we are indicating that we want to call the run() method on this object (RunnableClass is the object). We pass the argument “Created Thread” which is a string that becomes the name of the thread. The next few statements in the constructor will display information about the newly created thread. The information displayed is the name, the priority and the group of the thread.

The run method of the RunnableClass is going to execute a loop with 7 iterations. On each iteration is going to execute the next 2 statements:

System.out.println(t2.getName()  + ” ” + i);
Thread.sleep(300);

The first statement gets the name of the newly created thread called “t2” using the getName() method and concatenates the name with the iteration number. After that, it goes to sleep or 300 milliseconds.

A try/catch block is use to sorround the 2 statements because sleep() method might throw an InterruptedException. After the last iteration in the loop the following statement is executed:

System.out.println(“Exiting ” + t2.getName());

The statement will display a message indicating that the program is exiting the thread. The getName() method is used to extract the name of the thread.

On the other hand inside the main method of the MainClass we have the following lines of code:

Thread t1 = Thread.currentThread();
t1.setName(“MainThreadRenamed”);
RunnableClass rc = new RunnableClass();
rc.t2.start();

The first line is used to get a reference to the MainClass main method thread. In the second line we changed the name of the MainClass main method to “MainThreadRenamed”, in this example we are doing this just to demonstrate that the main method can be controlled just like any other thread. From this point on in the MainClass the main() method is no longer called main but is called MainThreadRenamed”.

The third line instantiates the RunnableClass, and the fourth line calls the start() method of the RunnableClass. This causes the child thread’s for loop to start. Next, the main thread (renamed to “MainThreadRenamed”) enters in a loop that iterates only 3 times and executes the following statements:

System.out.println(t1.getName() + ” ” + i);
Thread.sleep(1000);

The first line displays the name of the MainClass main thread (“MainThreadRenamed”) concatenated with the iteration number. Next, it pauses for one second by calling the sleep() method.  Both threads will share CPU time until they both finish. See below an output of the running of the programs in our system, remember the output may vary depending on the system it runs.

A Child thread was just instantiated
The Child thread name is [Created Thread] its priority is: [5] and its group is [main]
MainThreadRenamed 0
Created Thread 0
Created Thread 1
Created Thread 2
Created Thread 3
MainThreadRenamed 1
Created Thread 4
Created Thread 5
Created Thread 6
MainThreadRenamed 2
Exiting Created Thread
MainThreadRenamed thread finishing run.

 

Note:

It is good to let the main thread to finish last. In the previous programs we ensure the main thread to finish last by using a larger amount of milliseconds in the sleep() method, (we used 1000 in the main thread and 300 in child thread). Since the child thread uses a smaller number of milliseconds in its sleep() method, it always finishes before the main thread.

Multithreading Java Example – Example 3

In this example, we are using the technique in which we extend the Thread class, then we create an instance of that class.  The entry point for the new thread is the run() method, which must be overridden in the class that extends Thread.  As always we do not call the run() method directly, but we call start() method to execute the run() method, and this will begin the execution of the new thread.

package extend.thread;

class ThreadExtendsClass extends Thread {

    ThreadExtendsClass() {

        super(“ThreadExtendsClass”);

        System.out.println(“Child thread: “ + this);

    }

    public void run() {

        int n = 5;

        try {

            for (int i = 0; i < n; i++) {

                System.out.println(“Child Thread: “ + i);

                Thread.sleep(300);

            }

        } catch (InterruptedException e) {

            System.out.println(“Child interrupted.”);

        }

        System.out.println(“Exiting child thread”);

    }

}

public class MainClass {

    public static void main(String[] args) {

        ThreadExtendsClass tec = new ThreadExtendsClass();

        tec.start();

        try {

            int n = 3;

            for (int i = 0; i < n; i++) {

                System.out.println(“Main Thread: “ + i);

                Thread.sleep(1000);

            }

        } catch (InterruptedException e) {

            System.out.println(“Main thread interrupted”);

        }

        System.out.println(“Main thread exiting”);

    }

}

The programs in this example are similar to the previous example.  We have a main program that contains a main() method. In the MainClass program we instantiate the class ThreadExtendsClass and then run the start() method. Next, we start a loop that iterates 3 times, and on each iteration, it displays a message with the name of the main class and the iteration number. On each line, we pause the loop for just one second.

The other program, the one that extends the thread class is  called ThreadExtendsClass and it contains a all to super() inside the constructor method. When you call the super()  the method you are invoking a Thread constructor form with the  following signature:

public Thread(String threadName)

where threadname is the name of the newly created thread.

Multithreading Java Example – Example 4

In this example, we will use more than two threads. Your program can spawn many threads, it can create as many as you need. In this example, we spawn four threads.

package multiple.threads;

class ChildThread implements Runnable {

    String childThreadName;

    Thread t;

    ChildThread(String name) {

        childThreadName = name;

        t = new Thread(this, childThreadName);

        System.out.println(“New Thread: “ + t);

    }

    public void run() {

        try {

            for (int i = 0; i < 6; i++) {

                System.out.println(childThreadName + ” thread”

                        + ” loop iteration “ + i);

                Thread.sleep(1000);

            }

        } catch (InterruptedException e) {

            System.out.println(“Interrupting “ + childThreadName);

        }

        System.out.println(“Finalizing “ + childThreadName);

    }

}

The MainClass starts and instantiates the ChildThreat class four times.

Next,  it runs the start() method for each instance, which will start a new  thread for each instance. Then MainClass main thread is put to sleep for 10 seconds. 10 seconds is enough time to allow all the children threads to run and finish, then the main thread is finalized.

ChildThread class implements the Runnable Interface so that the run() method in the ChildThread class will override the run() method from the Thread object “t” that is instantiated in this statement:

Thread t;

In the ChildThread constructor check the following statement:

t = new Thread(this, childThreadName);

“t” is an object of type Thread, and here we are instantiating it passing “this” which is an instance of the class ChildTread as the first argument. The second argument is the childThreadName which is a String, so as we can see the constructor just creates a new thread and displays the name of the thread. Next in the ChildThread program, we have the run() method. In the run() method we have a loop that executes 6 times, and it displays a string with the child thread name and the iteration number of the loop, then it calls sleep() for 1 second for each iteration.

Conclusion

In this article, we discussed how to use the currentThread() method of the Thread class to gain control of the running thread, in this case, the main thread. We talk about how to change a property of the main thread, in the first example, we changed the name of the thread. We also discussed other methods of the Thread class such as sleep(), setName(), getName() and how to handle the exceptions the methods might throw. We cover examples of using one thread, two threads and all the way to four threads in our examples.

 

 

 

Leave a Comment