×

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 Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.