×

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

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

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.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 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.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.