×

Thread Program in Java

Thread Program in Java

Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading, synchronization, context switching, and the join() method.

Adding Elements of an Array

The addition of elements can be done using multithreading. In multithreading, we can split a given array into two or more than two halves. For each half, one thread can be created, which does the summation. Finally, a cumulative sum of all the resultants is done to get the answer. See the following code.

FileName: AddElements.java

 // importing packages
import java.util.*;
//random thread class
public class AddElements implements Runnable
{
    // two private fields of the class AddElements
    private int []array;
    private int s; // for the starting index
    private int e; // for the ending index
    // for doing the cumulative sum of the two halves
    // of the input array
    static int cumulativeSum = 0;
    // Parameterized constructor for initializing the fields
    AddElements(int []a, int s, int e)
    {
        this.array = a;
        this.s = s;
        this.e = e;
    }
    @Override
    public void run()
    {
        // invoking the method add
        add(array, s, e);
    }
    // method for adding elements
    void add(int arr[], int start, int end)
    {
        int sum = 0;
        // iterating over elements
        for(int i = start; i < end; i++)
        {
            sum = sum + arr[i];
        }
        // doing the cumulative sum of the two halves
        AddElements.cumulativeSum = AddElements.cumulativeSum + sum;
    }
   // main method
   public static void main(String argvs[]) throws InterruptedException
   {
       // input array
       int arr[] = {56, 78, 97, 89};
       // size of the array
       int size = arr.length;
       // the first object of the class AddElements
       AddElements ae1 = new AddElements(arr, 0, size / 2);
       // the second object of the class AddElements
       AddElements ae2 = new AddElements(arr, size / 2, size);
       // creating two threads
       // the first thread does the sum of the
       // first half of the input array
       Thread th1 = new Thread(ae1);
       th1.start();
       // the second thread does the addition of the
       // second half of the input array
       Thread th2 = new Thread(ae2);
       th2.start();
       // main thread waiting for
       // the first thread to finish its task
       th1.join();
       // main thread waiting for
       // the second thread to finish its task
       th2.join();
       // printing the result
       System.out.println("Sum of the elements of the given array is: " + AddElements.cumulativeSum );
   }
} 

Output:

Sum of the elements of the given array is: 320

Explanation: We have created two objects of the AddElements class which implements the runnable interface. For each object, a thread is created. Both threads call the method add(), and do the addition of elements of their respective parts. The static variable cumulativeSum receives the results of the work done by the two threads and does the summation of those resultants. Eventually, we are displaying the result. Note that the cumulativeSum variable has to be static to get the correct result. This is because the memory allocation of the static variables happens only once and is independent of the number of objects or threads created.

Race Condition and Ambiguity in Multithreading

In multithreading, when two or more than two threads try to access the same resource at the same time, the state of race condition is reached. Also, a multithreading program may result in ambiguous behavior. Let’s understand it with the help of an example.

FileName: MyClass.java

 // MyClass is inheriting the Thread class
public class MyClass extends Thread
{
// a global counter
static int counter = 0;
// a method for increment the value of the counter by 1
static void increment()
{
    // incrementing the value counter 100000 times for each thread
    for(int i = 0; i < 100000; i++)
    {
        counter++;
    }
}
@Override
public synchronized void run()
{
increment(); // invoking the method increment()
// getting the name of each of the thread
String threadName = Thread.currentThread().getName();
// displaying the result for each of the thread.
System.out.println("Value of the variable sum for " + threadName + " is " + counter);
}
// main method
public static void main(String args[])
{
    // creating two objects of the class MyClass1
    MyClass1 obj1 = new MyClass1();
    MyClass1 obj2 = new MyClass1();
    // creating two threads
    obj1.start();
    obj2.start();
}
} 

Output:

 Value of the variable sum for Thread-1 is 146837
Value of the variable sum for Thread-0 is 103188 

Explanation: In the above code, the static variable counter is shared between the two threads. Every thread is updating the value of the variable counter. Notice, no copy of the counter variable is made as counter is the static variable. Thus, the same resource (the counter variable) is shared between more than one thread, and each thread is fighting to increment the value of the counter variable by invoking the method increment(), and it is said race condition has occurred in the program.

Also, the general intuition says, first, Thread-0 is created; hence, it should be executed first, and then Thread-1. Thus, the value of the variable counter for Thread-0 should be printed first, then for Thread-1. However, the output says the opposite. Also, every thread is executing the for-loop and incrementing the value of counter variable; therefore, the final value of the variable counter should be 100000 + 100000 = 200000. However, the output never displays 200000.

Even the output mentioned above is not static! Every time the above program is executed, a different output is generated for threads 1 and 2. In the above code, these ambiguous behaviors should be ironed out.

Critical Section Synchronization Context Switching

There is one important aspect that is ignored in the above program. The absence of synchronization in the critical section of the program. Synchronization of the critical section means only one thread is allowed to enter the critical section.

Critical Section

The code which contains the resource that is shared between two or more than two threads is called the critical section of the program. In the above code, the increment() method is the critical section. This is because it contains the static variable counter that is shared between the two threads. In the above code, both the threads can enter the critical section and increment the counter variable. This leads to ambiguous results.

Context Switching

Thread-1 may start the for-loop even when Thread-0 has not finished the execution of for-loop. This is because switching between the threads execution, also known as context switching, is the duty of the Operation System, which can not be controlled by any Java program. In context switching, the Operation System holds the execution of one thread and executes another thread. After sometimes, the execution of the running thread is stopped, and the waiting thread starts its execution. This context switching happens continuously till the threads complete their execution.

We have learnt that we can not control context switching. However, we can easily control the number of threads entering the critical section. With the help of the above control, we can remove some of the ambiguity of the above program. Observe the following code.

FileName: MyClass1.java

 // MyClass is inheriting the Thread class
public class MyClass1 extends Thread
{
// a global counter
static int counter = 0;
// a method for increment the value of the counter by 1
static synchronized void increment()
{
    // incrementing the value counter 100000 times for each thread
    for(int i = 0; i < 100000; i++)
    {
        counter++;
    }
}
@Override
public void run()
{
increment(); // invoking the method increment()
// getting the name of each of the thread
String threadName = Thread.currentThread().getName(); 
// displaying the result for each of the thread.
System.out.println("Value of the variable sum for " + threadName + " is " + counter); 
}
// main method
public static void main(String args[])
{
    // creating two objects of the class MyClass
    MyClass obj1 = new MyClass();
    MyClass obj2 = new MyClass();
    // creating two threads
    obj1.start();
    obj2.start();
}
} 

Output:

 Value of the variable sum for Thread-0 is 105541
Value of the variable sum for Thread-1 is 200000 

Explanation: Using the synchronization keyword, we ensured the critical section is executed by only one thread at a time. Therefore, no matter what happens, one thread is going to finish at 200000. This is because simultaneous increment of the static variable counter is ruled out. Since we can not control the context switching, the value of the variable counter for one thread keeps on changing when the above code is executed again and again. Because of the uncontrolled context switching, it is also not clear which thread will finish its execution first.  

The Join() Method

Another approach to solve the ambiguous behavior is to use the join() method. We know that context switching is leading to the uncertain outcome when the code is executed every time. Also, controlling the context switching is impossible. However, context switching can only happen when there is more than one thread executing concurrently, and the spawning of threads can easily be controlled by the join() method. The following program illustrates the same.

FileName: MyClass2.java

 // MyClass is inheriting the Thread class
public class MyClass2 extends Thread
{
// a global counter
static int counter = 0;
// a method for increment the value of the counter by 1
static synchronized void increment()
{
    // incrementing the value counter 100000 times for each thread
    for(int i = 0; i < 100000; i++)
    {
        counter++;
    }
}
@Override
public void run()
{
increment(); // invoking the method increment()
// getting the name of each of the thread
String threadName = Thread.currentThread().getName(); 
// displaying the result for each of the thread.
System.out.println("Value of the variable sum for " + threadName + " is " + counter); 
}
// main method
public static void main(String args[]) throws InterruptedException
{
    // creating two objects of the class MyClass2
    MyClass2 obj1 = new MyClass2();
    MyClass2 obj2 = new MyClass2();
    // creating two threads
    obj1.start();
    // main thread is waiting for the first thread
    // to finish the task
    obj1.join();
    obj2.start();
}
} 

Output:

 Value of the variable sum for Thread-0 is 100000
Value of the variable sum for Thread-1 is 200000 

Explanation: Observe the second last statement of the main method. obj1.join(); is the new statement introduced in the code which is responsible for the elimination of all the ambiguity. It is obvious that the main thread is spawning the two new threads, one is Thread-0 and another is Thread-1. After the spawning of Thread-0, the main thread is executing the statement obj1.join();. The join() method puts the main thread in the waiting state till the Thread-0 finishes its execution. Thus, only Thread-0 is entering the critical section. Therefore, Operating System can not do the context switching. Therefore, no matter what happens, Thread-0 comes in the output before Thread-1.

After the completion of the task by Thread-0, the main thread spawns the Thread-1. Again, this time also, context switching can not happen because only one child thread is present in the program. Therefore, the output of the above program is always consistent. Try to execute the program again and again and observe the output remains the same every time.

Note that the statement obj1.join() ensures that only a child thread is present in the system. Hence, there is no chance of race condition. Therefore, we can eliminate the keyword synchronized from the method increment(). The output still remains the same.


Related Topics

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.